Iterator in Java
The Iterator interface in Java provides a standard way to traverse elements in a collection one by one without exposing the underlying data structure. It b...
Traversing Collections with Iterator
The Iterator interface in Java provides a standard way to traverse elements in a collection one by one without exposing the underlying data structure. It belongs to the java.util package and declares three core methods: hasNext(), which returns true if more elements remain; next(), which returns the next element; and remove(), which deletes the last element returned by next() from the underlying collection.
Every class that implements the Iterable interface, including all standard Collection types, can produce an Iterator via the iterator() method. The enhanced for-each loop in Java is actually syntactic sugar that compiles down to an Iterator-based loop, so understanding Iterator helps you understand what happens behind the scenes.
List<String> fruits = new ArrayList<>(List.of("Apple", "Mango", "Grape")); Iterator<String> it = fruits.iterator(); while (it.hasNext()) { String fruit = it.next(); if (fruit.equals("Mango")) { it.remove(); // safe removal during iteration } } System.out.println(fruits); // [Apple, Grape]
One of the most important uses of Iterator is the ability to safely remove elements while iterating. Calling the collection's own remove() method inside a for-each loop throws a ConcurrentModificationException. Using Iterator.remove() avoids this because the iterator keeps track of the structural state of the collection.
Java also provides ListIterator, an extended version that works only with List implementations. ListIterator allows bidirectional traversal and supports add() and set() operations in addition to remove().
Iterators are fail-fast by default in most Java collections. If the collection is structurally modified during iteration by any means other than the iterator itself, a ConcurrentModificationException is thrown immediately to prevent unpredictable behavior.
Interview tip: A frequent interview question is how to remove elements from a collection while iterating without throwing ConcurrentModificationException. The correct answer is to use Iterator.remove() rather than the collection's own remove() method.