An Iterator is an object that implements the Iterator Design Pattern, allowing sequential traversal across any Collection while safely abstracting away the underlying data structure.
Iterator Interface (Forward Only)import java.util.ArrayList;
import java.util.Iterator;
public class IteratorDemo {
public static void main(String[] args) {
ArrayList<String> cities = new ArrayList<>();
cities.add("Mumbai");
cities.add("New York");
cities.add("London");
cities.add("Tokyo");
Iterator<String> it = cities.iterator();
while (it.hasNext()) {
String city = it.next();
// Safe removal during iteration:
if (city.equals("London")) {
it.remove(); // Safely removes without ConcurrentModificationException!
}
}
System.out.println("Remaining cities: " + cities); // [Mumbai, New York, Tokyo]
}
}
ListIterator Interface (Bidirectional Traversal)Available exclusively for List implementations:
import java.util.List;
import java.util.ListIterator;
public class ListIteratorDemo {
public static void main(String[] args) {
List<Integer> nums = List.of(10, 20, 30);
ListIterator<Integer> lit = nums.listIterator(nums.size()); // Starts at end!
System.out.print("Reverse Traversal: ");
while (lit.hasPrevious()) {
System.out.print(lit.previous() + " "); // Output: 30 20 10
}
}
}
| Feature | Fail-Fast Iterators | Fail-Safe / Weakly-Consistent |
|---|---|---|
| Exception Thrown | Throws ConcurrentModificationException |
Never throws exception |
| Underlying Data | Operates directly on actual collection | Operates on a cloned copy or memory snapshot |
| Examples | ArrayList, HashSet, HashMap |
CopyOnWriteArrayList, ConcurrentHashMap |
Now let us explore how to sort custom objects using Comparable and Comparator. Proceed to: Comparable vs Comparator →
Accelerate your Java mastery by studying these tightly connected core tutorials:
Underlying iterator usage.
Traversing lists.
Bulk collection methods.
Sorting objects.