The Analogy: The Meter Reader's Route Sheet
A utility company sends a meter reader out each morning with a printed route sheet. The sheet lists the addresses to visit in a fixed order, and the reader works down it with a finger held between the line just done and the line coming next. The finger is a cursor: it does not sit on a house, it sits in the gap between houses. Two questions drive the whole walk. Is there another line below my finger? If so, move the finger down one and read the meter there. The reader never needs to know the house numbers in advance or how many houses remain; the sheet answers "is there a next one" and "give me the next one" and that is the entire protocol.
The reader may also strike a meter off. When a property is decommissioned the reader crosses out the line just read and notes it, and only that line -- the one the finger most recently passed -- may be struck. You cannot cross off a house you have not yet reached, and you cannot cross off two in a row without reading between them. Removing a line this way is safe precisely because it is done through the same finger that is tracking the walk, so the finger stays consistent with the sheet.
Here is the safeguard that gives this lesson its name. The master route lives back at the depot, and every printed sheet carries the revision number the master held when it was printed. The reader memorises that number before setting out. If the scheduling office edits the live route while the reader is out -- inserts a new build, retires an address -- the master's revision number ticks up, and the sheet in the reader's hand is now stale. The moment the reader notices the mismatch, procedure is absolute: stop the walk, do not guess, return to the depot for a fresh sheet. The walk fails immediately and visibly rather than continuing on a sheet that no longer matches reality.
The failure mode is a reader who ignores the revision mismatch and keeps going. The meter book they hand in looks complete -- every line filled, neatly totalled -- but because the route changed underneath them they silently skipped number 14 and read number 12 twice. Nothing flagged the error; the book is internally tidy and externally wrong. A month later a customer disputes a bill and the company discovers the walk was corrupt from the third house on. Failing fast and loud at the mismatch would have cost one wasted morning; failing silently cost a month and a customer's trust.
Syntax or Core Structure
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class Route {
public static void main(String[] args) {
List<String> stops = new ArrayList<>(
List.of("12 Elm", "14 Oak", "16 Ash", "18 Fir"));
Iterator<String> it = stops.iterator();
while (it.hasNext()) {
String stop = it.next();
System.out.println("read: " + stop);
if (stop.equals("16 Ash")) {
it.remove(); // strike the line just read
}
}
System.out.println("left: " + stops.size());
System.out.println("list: " + stops);
}
}
Output:
read: 12 Elm
read: 14 Oak
read: 16 Ash
read: 18 Fir
left: 3
list: [12 Elm, 14 Oak, 18 Fir]
The while (it.hasNext()) loop asks the cursor whether a next element exists, and it.next() advances and returns it. The it.remove() strikes the element last returned -- the only structural change the loop can safely make -- so the walk finishes cleanly with three stops left.
Technical Depth: The Iterator Contract, Why for-each Is Sugar, And How Fail-Fast Protects You
The Iterator And Iterable Contract
Two small interfaces underlie every collection walk in Java. Iterator<E> is the cursor: hasNext() reports whether another element remains, next() advances and returns it, and the optional remove() deletes the element last returned by next(). Iterable<E> is anything that can hand out a fresh cursor, declaring the single method iterator(). Every collection in the framework implements Iterable, which is exactly what qualifies it for the for-each loop.
| Capability | Iterator | ListIterator | for-each |
|---|---|---|---|
| Advance forward | Yes | Yes | Yes (implicit) |
| Move backward | No | Yes | No |
| Remove current | Yes | Yes | No |
| Set or insert | No | Yes | No |
| Access the cursor | Yes | Yes | No |
The plain Iterator walks one way and can remove; ListIterator (see [[linkedlist]]) adds backward movement, set, and add; the for-each loop hides the cursor entirely, which is why it cannot remove.
for-each Is Sugar Over The Iterator
A for-each loop is not a distinct construct. The compiler rewrites for (E e : coll) { ... } into a while loop over coll.iterator(), calling hasNext and next. That rewrite is why a for-each cannot call remove -- it never names the iterator, so you have no handle to remove through. It is also why modifying the collection inside a for-each is dangerous: the hidden iterator is still watching for structural change, and it will react.
Fail-Fast And modCount
Most collections track a modCount -- an integer bumped on every structural change (add, remove, clear). When you obtain an iterator it records the current modCount as its expected value, and every next() and remove() checks that the collection's modCount still matches. If some other path mutated the collection in the meantime, the values diverge and the iterator throws ConcurrentModificationException at once, rather than returning a wrong or skipped element.
import java.util.ArrayList;
import java.util.List;
public class FailFast {
public static void main(String[] args) {
List<Integer> nums = new ArrayList<>(List.of(1, 2, 3, 4));
boolean threw = false;
try {
for (int n : nums) {
if (n == 2) {
nums.add(99); // structural change mid-walk
}
}
} catch (java.util.ConcurrentModificationException e) {
threw = true;
}
System.out.println("threw: " + threw);
System.out.println("size: " + nums.size());
}
}
Output:
threw: true
size: 5
The add bumped modCount, so the next hasNext/next cycle detected the mismatch and threw. The element was still added -- size is 5 -- but the walk aborted rather than continuing on a collection that no longer matched the cursor. Fail-fast is best-effort, not a guarantee: it is documented as a bug-detection aid, so never write logic that depends on the exception being thrown.
The Only Safe Way To Remove During Iteration
The lesson from fail-fast is not "never modify while iterating" -- it is "modify through the cursor". Iterator.remove updates the collection and the iterator's expected modCount together, so the two never diverge. Any other structural change during the walk -- list.remove, list.add, map.put on a new key -- bumps modCount behind the iterator's back and trips the check. When you need to drop several elements by a condition, either loop with an explicit iterator and call it.remove(), or use the removeIf(predicate) method, which does the cursor bookkeeping internally.
Fail-Safe And Weakly Consistent Iterators
Not every collection throws. The concurrent collections return iterators that never raise ConcurrentModificationException, trading strict currency for the ability to iterate a live, shared structure safely.
| Collection | Iterator behaviour | Sees concurrent writes? |
|---|---|---|
| ArrayList, HashMap, HashSet | Fail-fast (throws on mod) | No -- aborts instead |
| CopyOnWriteArrayList | Snapshot at iterator creation | No -- fixed snapshot |
| ConcurrentHashMap | Weakly consistent | May or may not, no throw |
| ConcurrentLinkedQueue | Weakly consistent | May or may not, no throw |
A CopyOnWriteArrayList iterator walks a frozen snapshot taken when the iterator was created, so later writes are invisible and remove through it is unsupported. A ConcurrentHashMap iterator is weakly consistent: it traverses without locking, reflects some concurrent updates and not others, and never throws. These are the right tools for shared state; they are the wrong tool when you actually want fail-fast to catch a single-threaded bug.
Writing Your Own Iterable
Because for-each is defined purely against Iterable, any class that implements it becomes loopable. The class below counts down and is usable directly in a for-each.
import java.util.Iterator;
import java.util.NoSuchElementException;
public class Countdown implements Iterable<Integer> {
private final int from;
public Countdown(int from) { this.from = from; }
@Override
public Iterator<Integer> iterator() {
return new Iterator<>() {
private int current = from;
@Override
public boolean hasNext() { return current > 0; }
@Override
public Integer next() {
if (!hasNext()) throw new NoSuchElementException();
return current--;
}
};
}
public static void main(String[] args) {
StringBuilder sb = new StringBuilder();
for (int n : new Countdown(4)) {
sb.append(n).append(' ');
}
System.out.println("seq: " + sb.toString().trim());
}
}
Output:
seq: 4 3 2 1
The hasNext guards the end and next throws NoSuchElementException if called past it, which is the contract every well-behaved iterator honours. With those two methods the class drops straight into a for-each with no further support.
Real World Example: A Meter Book That Skipped A House
A billing job walks a list of meters and drops any marked decommissioned, building the month's read list as it goes. The original author wrote the removal as a direct list.remove inside a for-each, and in testing it never threw, because the test fixture happened to decommission the last meter, where the walk was already ending. In production a middle meter was decommissioned and the run threw -- or worse, on a slightly different list, silently skipped the meter after it.
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
public class MeterBook {
record Meter(String id, boolean live) {}
// Broken: structural change through the list mid-walk.
static String brokenPass(List<Meter> meters) {
try {
for (Meter m : meters) {
if (!m.live()) {
meters.remove(m);
}
}
return "read " + meters.size();
} catch (java.util.ConcurrentModificationException e) {
return "ABORTED";
}
}
// Fixed: remove through the cursor.
static int fixedPass(List<Meter> meters) {
Iterator<Meter> it = meters.iterator();
while (it.hasNext()) {
if (!it.next().live()) {
it.remove();
}
}
return meters.size();
}
public static void main(String[] args) {
List<Meter> a = new ArrayList<>(List.of(
new Meter("M12", true),
new Meter("M14", false),
new Meter("M16", true),
new Meter("M18", false)));
List<Meter> b = new ArrayList<>(a);
System.out.println("broken: " + brokenPass(a));
System.out.println("fixed: " + fixedPass(b));
System.out.println(String.format(Locale.ROOT,
"live: %d", b.size()));
b.forEach(m -> System.out.println("keep: " + m.id()));
}
}
Output:
broken: ABORTED
fixed: 2
live: 2
keep: M12
keep: M16
The broken pass aborts because meters.remove(m) inside the for-each bumps modCount behind the hidden iterator, and the next cycle detects the mismatch and throws. The fixed pass does the identical work -- drop every non-live meter -- but routes the removal through it.remove(), which updates the collection and the iterator's expected count together, so the walk finishes with the two live meters intact.
The subtle danger this example is built around is that the broken version passed its tests. Fail-fast is best-effort: whether the exception fires depends on where in the walk the modification lands and on the collection's internal state. Remove the last element and the loop is often already terminating, so no check runs and nothing throws -- the code looks correct. Remove a middle element and it throws, or on some list shapes silently returns a wrong result. A green test suite proved nothing here; only understanding the contract did.
The right mental model is that the collection and any live iterator over it are a matched pair, and the only edit that keeps them matched is one made through the iterator itself. Everything else desynchronises them. That is not a limitation to work around but the mechanism that turns a whole category of silent data corruption into a loud, immediate, stack-traced failure at the point of the mistake.
The genuine limit worth naming is that fail-fast cannot see cross-thread modification reliably and is explicitly not a concurrency control -- two threads sharing a plain ArrayList can corrupt it without any exception. For shared state you need a concurrent collection with a weakly consistent iterator, or external synchronisation. The design flaw in the broken pass was not the removal but choosing a for-each, which deliberately hides the cursor, for a loop that needed to remove; the construct's convenience was exactly the wrong fit for the job.
Common Mistakes
- Calling
list.removeinside a for-each. The hidden iterator sees themodCountjump and throwsConcurrentModificationException. Loop with an explicitIteratorand callit.remove(), or useremoveIf.
- Depending on fail-fast to fire. Whether the exception throws depends on where the modification lands; it is a best-effort bug aid, not a guarantee. Never gate program logic on catching it.
- Calling
next()withouthasNext(). Running off the end throwsNoSuchElementException. Always guardnextwithhasNext, or bound the loop by a known count.
- Calling
remove()beforenext(), or twice in a row.Iterator.removedeletes the element last returned bynext; with no such element it throwsIllegalStateException. Call it exactly once pernext.
- Assuming a for-each can remove. The desugared loop never names the iterator, so there is no handle to remove through. Use an explicit iterator when the loop must delete.
- Expecting a
CopyOnWriteArrayListiterator to see later writes. It walks a snapshot fixed at creation, and itsremoveis unsupported. Re-obtain the iterator to see newer state.
- Reusing an exhausted iterator. Once
hasNextreturns false the iterator is spent; there is no reset. Calliterable.iterator()again for a fresh walk.
- Treating a weakly consistent iterator as a consistent snapshot. A
ConcurrentHashMapiterator may reflect some concurrent updates and miss others. Do not assume it shows the map as it was at any single instant.
- Implementing
Iteratorwithout honouringnext's end contract. Returning junk or looping forever past the end breaks every for-each over the type. ThrowNoSuchElementExceptionwhenhasNextis false.
Best Practices
- Remove during iteration only through
Iterator.removeorremoveIf. These keep the collection and the cursor's expectedmodCountin step; every other structural edit desynchronises them.
- Prefer
removeIf(predicate)for conditional bulk removal. It expresses the intent in one line and does the iterator bookkeeping internally, removing the chance of a hand-rolled mistake.
- Guard every
next()withhasNext(). It is the contract the loop is built on and the only way to avoidNoSuchElementExceptionon an empty or exhausted cursor.
- Reach for a for-each when you only read. It is the clearest construct for a read-only walk; switch to an explicit iterator precisely when you must remove.
- Use concurrent collections for shared iteration.
ConcurrentHashMapandCopyOnWriteArrayListgive iterators safe to walk while other threads write; a plain collection needs external synchronisation.
- Do not rely on the fail-fast exception in production logic. Treat it as a development-time signal that a bug exists, then fix the bug rather than catching the symptom.
- Honour
NoSuchElementExceptionin custom iterators. A well-behavednextthrows past the end so that for-each and every other client can trust thehasNext/nextprotocol.
- Implement
Iterableto make a type loopable. Oneiterator()method drops your class into for-each; keep each returned iterator independent so nested loops over the same object do not interfere.
Practice Exercises
- The Loop That Aborted. Build an
ArrayList<Integer>and try to remove every even number with alist.removeinside a for-each; catch and report theConcurrentModificationException. Then rewrite it two ways -- with an explicit iterator andit.remove(), and withremoveIf-- and confirm both leave only the odd numbers, explaining why the cursor-based edits do not throw.
- A Ring You Can Loop. Write a class
Ring<T>implementingIterable<T>that yields a fixed number of laps over a backing array, sonew Ring<>(new String[]{"a","b"}, 3)iterates a, b, a, b, a, b. HavenextthrowNoSuchElementExceptionpast the last lap, and drive it with a for-each that builds the sequence into a string.
- Fail-Fast Versus Weakly Consistent. Populate an
ArrayListand aConcurrentHashMap's key set with the same values. In each, obtain an iterator, perform a structural modification through the collection, then continue iterating. Report which one throws and which completes, and explain in two sentences why the concurrent collection chooses not to fail fast.