100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
Java

Iterator in Java

Learn how to safely traverse and modify collections using Iterator, and why direct modification during a for-each loop throws ConcurrentModificationException.

Collections FrameworkIntermediate8 min readJul 7, 2026
Analogies

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

text
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

java
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

text
After Iterator removal: [1, 3, 5]
Caught: ConcurrentModificationException

6. 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

Was this page helpful?

Topics covered

#Java#JavaProgrammingStudyNotes#Programming#IteratorInJava#Iterator#Syntax#Explanation#Example#Loops#StudyNotes#SkillVeris