Skip to content

Try “polymorphism”, “TCP handshake” or “git rebase”.

    Java / Collections, From the Inside

    Iterating Safely

    An Iterator walks through a collection: hasNext(), next(), and remove() (removes the last element returned, safely). The for-each loop

    Chapter 3 of 112 min read

    The Plain Picture#

    You're counting people in a queue by walking along it. If people keep leaving and joining while you walk, your count is nonsense. A strict counter stops and complains the moment the queue changes behind their back.

    The Real Names#

    • An Iterator walks through a collection: hasNext(), next(), and remove() (removes the last element returned, safely). The for-each loop uses an iterator behind the scenes.

    • Java's standard collections have fail-fast iterators: if the collection is structurally modified (elements added or removed) during iteration by anything other than the iterator itself, the next next() throws ConcurrentModificationException. They detect it with an internal modification counter (modCount) that the iterator compares on each step.

    Under the Hood#

    Java
    List<Integer> scores = new ArrayList<>(List.of(40, 180, 90, 200, 60));
    
    for (Integer s : scores) if (s < 100) scores.remove(s); // modifying while for-each iterates
    // ConcurrentModificationException

    Two correct ways:

    Java
    Iterator<Integer> it = scores.iterator();
    
    while (it.hasNext()) if (it.next() < 100) it.remove(); // remove THROUGH the iterator
    
    // [180, 200]
    
    scores.removeIf(s -> s < 100); // simplest: removeIf with a condition
    // [180, 200]

    (A third option: loop backwards by index and call remove(i) — removing later elements doesn't shift earlier ones.)

    Despite the name, ConcurrentModificationException usually has nothing to do with threads — it's almost always one thread modifying a collection inside its own loop. For real multi-threaded access, use concurrent collections (Concurrency).

    Check yourself

    3 questions
    1

    What does "fail-fast iterator" mean?

    Show answer

    It throws ConcurrentModificationException as soon as it detects the collection was structurally modified outside the iterator.

    2

    Give two correct ways to remove elements while looping.

    Show answer

    iterator.remove(), removeIf(condition) (or looping backwards by index).

    3

    Does ConcurrentModificationException mean you have a threading bug?

    Show answer

    Usually not — typically it's the same thread modifying the collection inside a for-each loop.