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. What usually goes wrong. What you see What caused it How to fix it --- --- --- Some values that should have been deleted are still in the list Removing at index i slid the next element into i, then i++ jumped straight over it Skip the increment on any pass where you removed, or walk the list ba
Challenge: Remove the Evens