I have a for loop looping through an ArrayList.
If a condition is met in the for loop:
- I remove the current element from the
ArrayList - reduce the size of the
ArrayListlocal variable - reduce the for loop’s index like so, checking to ensure that they never go below zero.
A case where we have just removed the last element of the ArrayList:
i = (i > 0) ? i-- : i;
My problem is that the above does not reduce i by 1 when i > 0. I’ve used ternary operators countless times, but never seen this behavior. I’ve tested that i is indeed > 0 and that the i– section is being called. It simply isn’t reducing the value of i. Removing the 0 value check and simply running i--; does indeed reduce i as expected.
EDIT2: Ok, well someone edited out my last edit where I mentioned that I am specifically NOT using a ListIterator in this case due to the performance sensitive nature of the loop itself, being in a critical portion of Android code.
i--decrementsi, but returns the original value.i = i--will decrementi, then assign it to its original value.You should use
i - 1.