Java ternary operator and installation loop index values

I have a for loop loop through ArrayList.

If the condition is satisfied in the for loop:

  • I delete the current item from ArrayList
  • reduce the size of a local variable ArrayList
  • reduce the index of the for loop so that they never drop below zero.

The case when we just deleted the last item ArrayList:

i = (i > 0) ? i-- : i;

My problem is that the above does not reduce me by 1 for i> 0. I have used triple operators countless times, but have never seen this behavior. I tested that I really> 0, and that the i-section is being called. It just does not reduce the value of i. Removing a check of a value of 0 and simple execution i--;really reduces i as expected.

EDIT2: Well, someone edited my last edit, where I mentioned that in this case I specifically DO NOT use ListIterator due to the performance sensitivity of the loop itself, which is in the critical part of Android code.

+3
source share
8 answers

i--decreases i, but returns the original value.

i = i--will decrement iand then assign it to its original value.

You must use i - 1.

+6
source

The smallest fix:

Perhaps you follow these steps:

for (int i = 0; i < l.size(); i++) {         <--------------------------------.
    if (cond) {                                                               |
        l.remove(i);                                                          |
        i--;              // even if i == -1, it will be set back to 0 here --'
    }
}

Iterate back:

Another common solution is to iterate backwards, for example:

for (int i = l.size() - 1; i >= 0; i--) {
    if (cond) {
        l.remove(i);
    }
}

Usage ListIterator(unless critical performance is high):

ListIterator:

Iterator<String> iter = l.iterator();
while (iter.hasNext()) {
    if (shouldRemove(iter.next())
        iter.remove();
}
+4

?:

i = (i > 0) ? --i : i;

.

+3

, i = i-- ( i > 0), : ? :

i = (i > 0) ? i - 1 : i;

:

if (i > 0)
    i--;
+2

: , .

+2

, , , : ArrayList O (n), ArrayList O (n ^ 2) .

:

  • ArrayList
  • ArrayList , ArrayList

O (n), ( , ..)

+2

noop.

(i > 0) { -- }

( ).

+1

, i-- i , , , .

--i, , --, i, , i .

You'd better just do i-1one that won't set the value itwice:

i = (i > 0) ? i-1 : i;

All that was said, since the false version of the tee does nothing, you probably would be better off just using a simple one if():

if(i > 0) { i--; }

It is easier to read, it does not matter what the path is around --, and does no unnecessary processing, regardless of the result.

+1
source

All Articles