Lesson · Collections Framework
Iterators: the walk beneath for-each
15 min readIterators & Iteration
for-each is sugar for an Iterator loop, and the Iterator contract has teeth: one legal removal, a modification count that throws, and sibling iterators with different guarantees.
for-each is sugar
The loop you write every day, and the loop the compiler compiles it into:
for (String name : names) { System.out.println(name); } // the compiler writes: for (Iterator<String> it = names.iterator(); it.hasNext(); ) { String name = it.next(); System.out.println(name); }
Predict: the loop is two method calls on an Iterator. Everything odd about iteration in Java follows from that expansion: the removal rule, the modification count, the different flavours of iterator.
The Iterator contract
Three methods, four rules:
hasNext()answers whether another element is available.next()returns the next element and moves the cursor past it.- Calling
next()past the end throwsNoSuchElementException. remove()erases the element last returned bynext(). Called twice in a row, or before anynext(), it throwsIllegalStateException.
The reason the rule exists: for-each gives you elements, not the iterator, so it can never offer you remove(). Deleting while looping needs the explicit iterator, and the demo shows exactly how.
Cursor lab · the iterator contract, live
drive the iterator by handThe list
Iterator log
iterator created over [ada, grace, alan]
Try: next(), next(), remove(), then remove() again. Reset, then add "boom" in the middle of the walk and call next(): the modification count ends the iterator.
Iterable is the doorway
for-each works on any type that implements Iterable, not only collections. Your own counted sequence qualifies:
static class Countdown implements Iterable<Integer> { private final int from; Countdown(int from) { this.from = from; } public Iterator<Integer> iterator() { return new Iterator<>() { private int next = from; public boolean hasNext() { return next > 0; } public Integer next() { return next--; } }; } } for (int n : new Countdown(3)) { System.out.print(n + " "); // 3 2 1 }
- Collection extends Iterable. That single relationship is why for-each,
stream()andremoveIfwork on every collection ever written. - Iterator is one-shot. Once it returns false from
hasNext(), it is spent; a new loop needs a new iterator.
ListIterator: both directions
Lists hand out a richer cursor: it sits between elements, can walk backwards, and can rewrite what it passes over.
list.listIterator()starts at the front;list.listIterator(index)starts elsewhere;listIterator(size())starts past the end.previous()andhasPrevious()mirrornext()andhasNext().set()replaces the last returned element;add()inserts at the cursor. Both keep the walk legal.- Being at the cursor is a position between elements: a backwards walk from the end visits every element in reverse.
The demo's backwards walk prints alan ada: a listIterator(size()) moves left through the list without copying it.
Fail-fast and fail-safe
Most iterators count structural modifications and compare the count on every step. Change the collection behind an active iterator and the next step throws:
| Iterator flavour | Example | Sees later changes | Throws on change |
|---|---|---|---|
| fail-fast | ArrayList, HashMap, TreeSet | yes, because it reads the live data | yes: ConcurrentModificationException |
| snapshot (fail-safe) | CopyOnWriteArrayList, CopyOnWriteArraySet | no: it iterates a frozen copy | no |
| weakly consistent | ConcurrentHashMap, ConcurrentLinkedQueue | maybe, with no promise either way | no |
- Fail-fast is a bug detector, not a lock. It catches single-threaded mistakes such as adding during for-each; it provides no thread safety by itself.
- The one legal change during a fail-fast walk is
iterator.remove(), which updates the modification count in step with the cursor. - Fail-safe iterators trade freshness for stability: they never throw under modification, because they never read the mutated structure directly.
Spliterators, in one paragraph
The streams API sits on Spliterator: a cursor that can also split itself in two for parallel work.
collection.stream()asks the collection for a Spliterator;parallelStream()lets it split repeatedly (trySplit) and hands the halves to worker threads.- A Spliterator advertises characteristics:
ORDERED,SIZED,DISTINCT,SORTED. They let the pipeline skip work instead of checking it at run time. - You will rarely implement one; knowing it exists explains why streams know a
HashSetis unsized for order and aTreeSetarrives sorted.
The iteration playbook
Sorting out iteration behaviour, in order:
- Prefer for-each; reach for an explicit Iterator only when you must remove.
- Removing is
iterator.remove()during a fail-fast walk, orremoveIfwhen the condition is simple. - Iterating shared, concurrently modified data? Choose the collection for its iterator flavour: snapshot or weakly consistent.
- Implement
Iterableon your own types to join the ecosystem for free. - Never assume an iterator sees writes that happen after it started; only fail-fast ones do, and then they throw.
The cursor is the whole story. One position, a modification count, and a removal rule explain every iterator behaviour you will meet.
One cursor, one contract, three flavours
Iterator is a cursor with a three-method contract, and for-each is sugar over it. Fail-fast iterators read live data and throw on outside change; snapshot iterators read a frozen copy; weakly consistent iterators promise neither throw nor freshness. Removing during a walk is legal only through iterator.remove() on fail-fast iterators, and implementing Iterable is how your own types earn for-each.
Interview angles
What does for-each compile into?+
An Iterator loop: iterator(), then hasNext() and next() until it ends. That is why any Iterable can be for-each-ed, Map cannot, and removing during the loop is refused.
The compiler will not produce a call to remove(), because the loop variable gives access to elements only. When deletion is part of the job, the explicit iterator is the tool: it is the only object allowed to modify the collection during its own walk.
Common misconception: That for-each is a language feature over arrays extended to collections. Arrays are a separate compile-time path; collections go through the Iterator protocol.
Follow-up: Why does adding inside a for-each body throw?
What is the exact rule for iterator.remove()?+
It removes the element returned by the most recent next(), exactly once. Before any next(), or twice in a row, it throws IllegalStateException.
The rule keeps cursor and collection in agreement: after removal the cursor already points at the following element. Calling remove() again would make the walk either skip an element or revisit one, so the iterator refuses instead of guessing.
Common misconception: That remove() deletes the element the cursor points at. There is no such element: the cursor sits between elements.
Follow-up: How does a fail-fast iterator know an outside change happened?
What does fail-fast actually guarantee?+
That structural modification outside the iterator is detected by the next operation and reported as ConcurrentModificationException. It is a debugging aid for single-threaded mistakes, not synchronisation.
The mechanism is a modification count captured at creation and compared on each step. It is best effort: two threads racing can change the count between the check and the read. Real shared access needs the java.util.concurrent collections or explicit locking.
Common misconception: That fail-fast means thread-safe. It means fast to notice your own bug.
Follow-up: Which collections iterate without throwing while others write?
Compare fail-fast, snapshot and weakly consistent iterators.+
Fail-fast reads live data and throws on structure changes. Snapshot (CopyOnWriteArrayList) iterates a frozen copy, so it never throws and never sees later writes. Weakly consistent (ConcurrentHashMap) may or may not see concurrent changes, but never throws.
The choice is a trade: fail-fast is cheapest and detects bugs; snapshot costs a copy per write and is ideal for read-mostly lists; weakly consistent is built for concurrent maps where "some consistent view" is the right semantics.
Common misconception: That snapshot iterators are always better because they never throw. A snapshot can be badly stale, which is a correctness question, not just a freshness one.
Follow-up: Where does forEachRemaining fit in?
What is a Spliterator and when do you meet one?+
The iterator underneath streams: it walks elements and can trySplit itself for parallel work, while advertising characteristics such as ORDERED and SIZED. You meet it through stream() and parallelStream().
Characteristics are metadata for optimisation: a SORTED source tells the pipeline that sorted() is free; SIZED skips length discovery. Implementing one by hand is rare; understanding that it exists explains why parallel streams behave differently per collection type.
Common misconception: That streams replace iterators: streams are built on Spliterators, and collections still hand out both.
Follow-up: Why is a parallel stream over a HashSet less predictable than one over an ArrayList?