Iterators
Iterators in Java provide a standard, safe, and uniform way to traverse elements of a collection one by one. They are a fundamental part of the Java Collections Framework and are heavily tested in interviews, especially around fail-fast vs fail-safe behavior.
What Is an Iterator?
An Iterator is an object used to traverse a collection sequentially without exposing its internal structure.
- One-directional traversal
- Works with all Collection types
- Part of java.util package
Iterator<E> iterator = collection.iterator();
Why Iterators Are Needed
- Uniform traversal across collections
- Safe element removal during iteration
- Avoids index-based errors
- Supports polymorphism (List, Set, Queue)
Iterator Interface (Core Methods)
public interface Iterator<E> {
boolean hasNext();
E next();
void remove();
}
Basic Iterator Example
List<String> list = new ArrayList<>();
list.add("Java");
list.add("Python");
Iterator<String> it = list.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
✔ Sequential access
✔ Safe traversal
How Iterator Works (Execution Flow)
- iterator() creates iterator object
- hasNext() checks if element exists
- next() returns current element and moves cursor
- Loop continues until hasNext() is false
Removing Elements Using Iterator (Important)
Iterator<String> it = list.iterator();
while (it.hasNext()) {
String val = it.next();
if (val.equals("Java")) {
it.remove(); // safe removal
}
}
✔ Safe
❌ list.remove() inside loop → ConcurrentModificationException
Iterator vs for-each Loop
| Aspect | Iterator | for-each |
|---|---|---|
| Direction | Forward only | Forward only |
| Removal | ✔ Yes | ❌ No |
| Flexibility | High | Simple |
| Internal working | Explicit | Uses Iterator internally |
Iterator vs ListIterator (Preview)
| Feature | Iterator | ListIterator |
|---|---|---|
| Direction | Forward only | Bidirectional |
| Add elements | ❌ No | ✔ Yes |
| Replace elements | ❌ No | ✔ Yes |
| Works with | All Collections | List only |
Fail-Fast Iterators (Very Important)
Most Java collection iterators are fail-fast.
What Is Fail-Fast?
- Iterator throws ConcurrentModificationException
- Occurs when collection is modified structurally during iteration
- Detects bugs early
for (String s : list) {
list.add("C++"); // ❌
}
Fail-Safe Iterators (Contrast)
- Do not throw exception
- Work on a copy of collection
- Found in concurrent collections
Examples:
- CopyOnWriteArrayList
- ConcurrentHashMap
Iterator with Set and Map
Set
Iterator<Integer> it = set.iterator();
Map (via entrySet)
Iterator<Map.Entry<Integer, String>> it =
map.entrySet().iterator();
✔ Best practice for Map iteration
Common Beginner Mistakes
- Modifying collection directly during iteration
- Forgetting hasNext() check
- Calling remove() before next()
- Using iterator incorrectly with Map
Interview-Ready Answers
Short Answer
An iterator is used to traverse elements of a collection one by one.
Detailed Answer
In Java, an Iterator provides a uniform way to traverse collections. It supports forward-only traversal and allows safe removal of elements during iteration. Most iterators are fail-fast and throw ConcurrentModificationException if the collection is modified structurally during traversal.
Key Takeaway
Iterators provide safe, consistent traversal across collections. Use Iterator when you need controlled iteration and safe removal.