Why this matters
ConcurrentModificationExceptionis among the most common run-time failures in Java, and the fix depends on understanding why the check exists.- Comparators compose, and the fluent form has almost entirely replaced hand-written comparison logic.
- A comparator inconsistent with
equalsquietly breaks sorted collections, which is a subtle and genuinely hard bug.
How iteration works
The enhanced for loop is syntax over an iterator.
Iterator has three methods: hasNext(), next(), and remove() — the last being the only safe way to
delete during traversal.
Fail-fast
Most java.util collections track a modification count. The iterator records it at creation and
re-checks it on every next(). A mismatch means the collection changed structurally, and the iterator
throws rather than returning unpredictable results.
What counts as structural
- Adding or removing an element is structural, and invalidates every active iterator.
- Replacing a value with
set(index, value)orentry.setValue(...)is not structural and is safe. iterator.remove()updates the count the iterator is tracking, so it stays valid.- The check is best-effort, not a guarantee. Under concurrency it may miss a modification.
The rest of this guide is part of Pro
Free covers every fresher guide in full. Pro unlocks Senior, Staff and Architect guides across every track.
Still to come · 7 sections
- Removing safely
- Fail-safe iteration
- Comparable: the type's natural order
- Comparator: ordering from outside
- Comparable or Comparator
- Consistency with equals
- Common misreadings
Test yourself
Answer these before moving on — recall is what makes it stick.