Java Zero to All All questionsPractise free
Interview questions › Java Foundations — Zero to Basics › Control Flow — Loops, Conditionals & Switch

Why can an enhanced for-each loop throw ConcurrentModificationException, and how do you remove elements correctly?

Level II · JuniorControl Flow — Loops, Conditionals & Switch
Short answer

for-each desugars to an Iterator, and most collections track a modCount; structurally modifying the collection (add/remove) directly while iterating makes the iterator's expected count diverge, so the next call throws ConcurrentModificationException fail-fast.

Explanation

To remove during iteration, use the explicit Iterator.remove(), or Collection.removeIf(predicate) which handles it internally. Note this is a best-effort safety check, not a thread-safety guarantee.

Common mistakes
  • Calling list.remove() inside a for-each loop.
  • Not knowing Iterator.remove() or removeIf() are the safe ways.

Can you say this out loud in two minutes? Drill it in a timed mock interview, with flashcards and runnable code for Control Flow — Loops, Conditionals & Switch.

Practise free

More on Control Flow — Loops, Conditionals & Switch