1. Introduction
Iterator is an interface in the Collections Framework that provides a standard way to traverse elements of a collection one at a time, regardless of the underlying implementation (ArrayList, HashSet, HashMap's values, etc.).
Cricket analogy: Whether you're reviewing a scorecard from a one-day match or a T20, a single innings review process lets a commentator step through deliveries one at a time regardless of format, just like Iterator traversing an ArrayList, HashSet, or HashMap uniformly.
You obtain an Iterator by calling collection.iterator(). It exposes three key methods: hasNext() (checks if more elements remain), next() (returns the next element and advances), and remove() (removes the last element returned by next()).
Cricket analogy: A scorer calls next-over to start reviewing deliveries, checks hasNext() to see if the over isn't finished, calls next() for each ball, and can flag remove() to strike off a no-ball.
2. Syntax
Iterator<String> it = list.iterator();
while (it.hasNext()) {
String value = it.next();
if (value.equals("target")) {
it.remove(); // safe removal during iteration
}
}
// ListIterator - List-specific, bidirectional
ListIterator<String> lit = list.listIterator();
lit.hasPrevious();
lit.previous();
lit.set("newValue");3. Explanation
The for-each loop (enhanced for loop) is internally powered by Iterator, but it does not expose remove(). If you try to modify a collection directly (e.g., list.remove(x)) while iterating over it with a for-each loop, Java throws a ConcurrentModificationException because the collection's internal modCount changes unexpectedly between iterator checks.
Cricket analogy: The for-each loop is like a fixed pre-announced batting order card the umpire reads from; if the captain swaps a batsman mid-over without updating the card, the scorers hit a ConcurrentModificationException-style dispute because the order no longer matches.
Iterator.remove() is the only safe way to remove elements while iterating, because it updates the iterator's internal state (and the collection's modCount) consistently, avoiding the fail-fast check that triggers ConcurrentModificationException.
Cricket analogy: Only the official scorer, using the approved correction procedure, can amend a delivery mid-over without triggering a dispute, just as only Iterator.remove() can safely delete an element mid-traversal without breaking modCount consistency.
Exam trap: 'for (String s : list) { if (...) list.remove(s); }' compiles fine but throws ConcurrentModificationException at runtime. The fix is to use Iterator.remove() explicitly instead of modifying the collection directly inside a for-each loop.
ListIterator, obtained from a List via listIterator(), extends Iterator with bidirectional traversal (hasPrevious()/previous()) and in-place modification via set() and add().
4. Example
import java.util.*;
public class IteratorDemo {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6));
// Safe removal using Iterator
Iterator<Integer> it = numbers.iterator();
while (it.hasNext()) {
int n = it.next();
if (n % 2 == 0) {
it.remove(); // safely removes even numbers
}
}
System.out.println("After Iterator removal: " + numbers);
// Unsafe: would throw ConcurrentModificationException
try {
for (Integer n : numbers) {
if (n == 3) {
numbers.remove(n); // modifying directly during for-each
}
}
} catch (ConcurrentModificationException e) {
System.out.println("Caught: ConcurrentModificationException");
}
}
}5. Output
After Iterator removal: [1, 3, 5]
Caught: ConcurrentModificationException6. Key Takeaways
- Obtain an Iterator via collection.iterator(); use hasNext()/next() to traverse.
- Iterator.remove() is the only safe way to remove elements while iterating.
- Direct modification of a collection during a for-each loop throws ConcurrentModificationException.
- ListIterator extends Iterator with bidirectional traversal and set()/add() for Lists.
- For-each loops are syntactic sugar over Iterator but don't expose remove().
Practice what you learned
1. Which method do you call on a Collection to obtain an Iterator?
2. What exception is thrown if you modify a List directly while iterating with a for-each loop?
3. Which method safely removes an element while iterating?
4. Which interface extends Iterator with bidirectional traversal for Lists?
5. What are the three core methods of the Iterator interface?
Was this page helpful?
You May Also Like
ArrayList in Java
Learn how ArrayList works internally, its time complexity, and when to use it over arrays or LinkedList.
LinkedList in Java
Explore Java's doubly-linked LinkedList, its List and Deque capabilities, and how its performance contrasts with ArrayList.
HashMap in Java
Learn how HashMap stores key-value pairs using hashing, its null-key rules, and why iteration order is not guaranteed.
Related Reading
Related Study Notes in Programming
Browse all study notesApache Spark Study Notes
Programming · 30 topics
ProgrammingApache Flink Study Notes
Programming · 30 topics
ProgrammingHadoop Study Notes
Programming · 30 topics
ProgrammingSnowflake Study Notes
Programming · 30 topics
ProgrammingApache Airflow Study Notes
Programming · 30 topics
Programmingdbt (Data Build Tool) Study Notes
Programming · 30 topics