Iterator
An Iterator walks a collection one element at a time. hasNext and next move forward. remove deletes the last element returned, safely, during iteration.
Detailed Explanation
The enhanced for is syntax over an iterator. for (E e : list) calls iterator(), then hasNext/next, then close if the iterator is Closeable (streams of paths). You write an iterator yourself when you need to remove while walking, when you implement Iterable, or when you walk a structure that is not a Collection.
The contract is one-way. There is no previous on Iterator (see ListIterator). Calling next without hasNext throws NoSuchElementException. remove may be called at most once per next, and some iterators (List.of, unmodifiable lists) throw UnsupportedOperationException.
Fail-fast iterators from java.util watch a modCount. If the collection is structurally changed by anything except that iterator's remove, the next call throws ConcurrentModificationException. That check is best-effort, not a guarantee. It exists to catch bugs, not to provide concurrent correctness. Concurrent collections use weakly consistent iterators that do not throw and may miss or repeat an element.
You reach for an explicit iterator when you delete as you go (it.remove() after a test), when you need to walk two collections in lockstep, or when you implement Iterable so callers can use enhanced for. You keep enhanced for when you only read. You do not call list.remove(e) inside enhanced for; that is the fail-fast case.
The cost of a custom iterator is the state machine: you must not return the same element twice, and you must not skip. Spliterator is the parallel cousin used by streams. Iterable is the type that supplies iterators; Iterator is the cursor. A class can be iterable once and produce many independent iterators.
Iterator is not thread-safe. Sharing one cursor across threads needs external synchronization.
Code Examples
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class DropEven {
public static void main(String[] args) {
List<Integer> xs = new ArrayList<>(List.of(1, 2, 3, 4));
Iterator<Integer> it = xs.iterator();
while (it.hasNext()) {
if (it.next() % 2 == 0) {
it.remove(); // safe structural change
}
}
System.out.println(xs); // prints: [1, 3]
}
}import java.util.Iterator;
import java.util.List;
public class First {
public static void main(String[] args) {
Iterator<String> it = List.of("a", "b").iterator();
System.out.println(it.hasNext()); // prints: true
System.out.println(it.next()); // prints: a
System.out.println(it.next()); // prints: b
System.out.println(it.hasNext()); // prints: false
}
}Common Gotchas
`list.remove` inside enhanced `for` throws `ConcurrentModificationException`
use `Iterator.remove` or `removeIf`.
Fail-fast is not a lock
concurrent mutation is still a bug even if CME does not fire.
`next` without `hasNext` throws `NoSuchElementException`
do not catch that as control flow.
Unmodifiable collections reject `remove`
`UnsupportedOperationException`.