Java Iterators: Iterator, ListIterator and Fail-Fast vs Fail-Safe

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.

1. The 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]
    }
}

2. The 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
        }
    }
}

Fail-Fast vs. Fail-Safe Iterators

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

Next Step

Now let us explore how to sort custom objects using Comparable and Comparator. Proceed to: Comparable vs Comparator →

Frequently Asked Questions (FAQ)

Q1. What is the difference between Iterator and ListIterator in Java?
Iterator works with ANY Collection (Lists, Sets, Queues) and only traverses forward (hasNext(), next()). ListIterator works ONLY with Lists, supporting bidirectional traversal (hasPrevious(), previous()), index queries, and element replacement (set()).
Q2. What causes a ConcurrentModificationException in Java?
A ConcurrentModificationException is thrown by a fail-fast iterator when a collection's structural size is modified (via list.add() or list.remove()) by external code while an iteration is actively in progress.
Q3. How can you safely remove an element while iterating over a collection?
Use the iterator's own removal method: iterator.remove(). This removes the current element while properly synchronizing the iterator's internal modCount tracker.

Explore Related Java Tutorials

Accelerate your Java mastery by studying these tightly connected core tutorials:

Enhanced For-Each Loop →

Underlying iterator usage.

Java ArrayList →

Traversing lists.

Collections Utility Class →

Bulk collection methods.

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!