Removing Elements During Traversal
Part of: ArrayList
The Shifting Problem When you remove(i) from an ArrayList, every element after index i shifts left to fill the gap. If you are looping forward with an index and you remove an element, the next element slides into the slot you just left, so a naive i++ skips it: Fix 1: Do Not Increment After Removal Only advance i when you did not remove: After a removal you re-examine the same index, which now holds the shifted element. Fix 2: Traverse Backward Looping from the end to the start avoids the shift problem entirely, because removing index i only shifts elements at indices greater than i, which you have already visited: This is often the cleanest fix. Why Not for-each? You cannot remove inside an enhanced for loop. Structurally modifying the list during a for-each throws a ConcurrentModificationException. Always use an indexed loop (or an Iterator, which is beyond the AP subset) when removing. Summary - Removing shifts later elements left, so forward index loops can skip elements. - Either avoid incrementing after a removal, or traverse backward. - Never remove inside a for-each loop.
Challenge: Remove the Evens