Skip to main content
PreparationZone Logo
PrepZone

Iteration and Ordering

Fail-fast versus fail-safe, safe removal during a loop, and Comparable versus Comparator.

Pass checkpoint below

Read these first

Why this matters

  • ConcurrentModificationException is 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 equals quietly breaks sorted collections, which is a subtle and genuinely hard bug.

How iteration works

The enhanced for loop is syntax over an iterator.

Java
Loading compiler…

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.

Fail-fast — ArrayList, HashMap
Iterator startsRecords modCount
ConcurrentModificationException
Fail-safe — CopyOnWriteArrayList
Iterator startsTakes a snapshot
Loop finishes cleanlyChange not seen
Standard collections throw the moment the structure changes mid-loop. Concurrent collections iterate over a snapshot instead, so they never throw but can miss recent writes.
Java
Loading compiler…

What counts as structural

  • Adding or removing an element is structural, and invalidates every active iterator.
  • Replacing a value with set(index, value) or entry.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.