Iterator
TL;DR
- Iterator is an interface (
java.util.Iterator) used to loop through collections. - It provides a safe way to remove elements from a collection while iterating over it.
- Has three main methods:
hasNext(),next(), andremove().
Concept
Before the enhanced for-each loop was introduced in Java 5, Iterator was the standard way to traverse Lists, Sets, and Maps (via keySet() or entrySet()).
Today, while for-each loops are more readable, Iterator remains crucial for one specific reason: Safe Deletion. If you try to remove an item from a collection inside a standard for-each loop, Java will throw a ConcurrentModificationException. An Iterator avoids this.
Examples
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class IteratorExample {
public static void main(String[] args) {
List<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
names.add("Charlie");
// --- BAD: Throws ConcurrentModificationException ---
/*
for (String name : names) {
if (name.equals("Bob")) {
names.remove(name); // CRASH!
}
}
*/
// --- GOOD: Safe Removal with Iterator ---
Iterator<String> iterator = names.iterator();
while (iterator.hasNext()) {
String name = iterator.next();
if (name.equals("Bob")) {
// Must call remove on the iterator, NOT the list
iterator.remove();
}
}
System.out.println(names); // [Alice, Charlie]
}
}
Interview Questions
Q: What is the Iterable interface?
A: Iterable is the root interface for all Collections. If a class implements Iterable, it means it has a method called iterator() that returns an Iterator object. Any class that implements Iterable can be the target of the enhanced for-each loop syntax.
Q: Why does the for-each loop throw a ConcurrentModificationException when removing items?
A: Under the hood, the enhanced for-each loop is just syntactic sugar for using an Iterator. However, the loop hides the iterator reference from you. If you call list.remove() inside the loop, the list’s structural modification count changes, but the hidden iterator doesn’t know about it. On the next loop iteration, the iterator notices the mismatch and throws the exception to prevent unpredictable behavior. Calling iterator.remove() explicitly updates both the list and the iterator’s internal state.