AP® Computer Science A · Unit 4 · Topic 4.9

Removing While Traversing

Watch it explained

  1. How it worksHow does a remove pull the next element into the index the loop already went past?
  2. Worked exampleTrace removing every even number from 2, 4, 6, 7 with i++ and find which one survives.
  3. How it worksHow does looping backwards make deletion during a traversal completely safe?
  4. Common mistakeWhy doesn't an enhanced for loop let you remove an element safely?
  5. Worked exampleFind the exact moment a ConcurrentModificationException gets thrown inside a for-each loop.

Check yourself

Your turn1 of 2
Removing every even number from the list 2, 4, 6, 7 using for (int i = 0; i < list.size(); i++) { if (list.get(i) % 2 == 0) list.remove(i); } — which value incorrectly survives the removal?

End of topic.