skip to content

Iterators & Traversal

How collections are traversed — Iterator, ListIterator and Spliterator — and what happens when the collection changes underneath you. ConcurrentModificationException is the guaranteed follow-up question.

part ofJavaread it →
on this pageshow

explore

questions

16

What is a ConcurrentModificationException, and when does it typically occur?

level: juniorimportance: must knowfreq 78%

answer

  1. modCount vs expectedModCount
  2. structural = add/remove, or perturbs iteration
  3. usually single-threaded for-each bug
  4. fix: Iterator.remove / removeIf / copy
  5. fail-fast = throw at the next check

basics

~20 s

ConcurrentModificationException is the unchecked exception a fail-fast iterator throws, on a best-effort basis, when its collection is structurally modified outside the iterator during a loop. The classic case is list.remove(x) inside a for-each, with no threads involved.

solid answer

~50 s

ConcurrentModificationException (CME) signals that a collection was structurally modified while it was being iterated, in a way the iterator didn't expect. 'Structural' means adding or removing elements, or otherwise disturbing an iteration in progress as ArrayList.sort does, not just updating an existing element's value. The most common cause has nothing to do with multiple threads: it's modifying the collection directly (e.g. list.remove(x)) inside a for-each loop over that same collection. The for-each loop uses an iterator under the hood, and that iterator detects the modification on its next next() or remove() call and throws. hasNext() runs no check, so one removal while the loop is on an ArrayList's second-to-last element ends it silently with the last element unvisited. The fix is to either iterate over a copy, use Iterator.remove(), use removeIf(), or collect-then-modify. Despite the 'Concurrent' name, it is most often a single-threaded bug.

code

java · 15 lines
java
List<String> list = new ArrayList<>(List.of("a", "b", "c"));

// Throws ConcurrentModificationException on the next iteration
for (String s : list) {
    if (s.equals("a")) list.remove(s);
}

// Alternative (Java 8+): no loop left to interfere with
list.removeIf(s -> s.equals("a"));

// Alternative: remove through the iterator itself
Iterator<String> it = list.iterator();
while (it.hasNext()) {
    if (it.next().equals("a")) it.remove();
}

go deeper

for a junior

Recognizes the classic 'remove inside a for-each' bug and knows the standard fix (Iterator.remove or removeIf). Knows CME is usually a single-threaded mistake, not a threading issue.

for a middle

Can explain modCount/expectedModCount and what 'structural modification' precisely means (adding, removing or otherwise perturbing iteration, not a value change). Lists multiple correct fixes and knows set() is safe.

for a senior

Explains why fail-fast exists (avoid silent wrong results), that detection is best-effort and not a concurrency guarantee, and when to switch to concurrent collections instead.

for a principal

Frames CME as a bug detector, contrasts fail-fast vs weakly-consistent iterators as a library trade-off, and guides teams on choosing data structures for concurrent access patterns.

## The problem in one picture In Java, a **collection** is an object that holds a group of elements (a `List`, `Set`, `Map`, etc.). To visit every element you use an **iterator** — an object that walks the collection one element at a time via `hasNext()` and `next()`. The `for (T x : collection)` syntax (the **for-each loop**) is just syntactic sugar: the compiler turns it into an explicit iterator loop. **ConcurrentModificationException (CME)** is a `RuntimeException` (unchecked — you don't have to declare or catch it) thrown when the collection is **structurally modified** while an iterator is walking it. ## What 'structural modification' means A **structural modification** adds or removes elements (`add`, `remove`, `clear`, `addAll`, etc.) or otherwise perturbs the collection so that an iteration in progress could go wrong. A changed `size()` is the usual sign, not the definition: `ArrayList.sort` counts with the size unchanged, and in an access-ordered `LinkedHashMap` even `get` counts. **Not** structural: replacing an existing element's value in place, e.g. `list.set(i, newValue)` or `put(existingKey, newValue)` on a `HashMap` — these do **not** trigger CME. ## The classic bug (single-threaded) ```java List<String> list = new ArrayList<>(List.of("a", "b", "c")); for (String s : list) { // hidden iterator if (s.equals("a")) { list.remove(s); // structural modification of the SAME list } } // throws ConcurrentModificationException on the next iteration ``` Notice: **no threads involved.** You modified the list through the *list* while iterating through the *iterator*; the iterator notices the change underneath it and refuses to continue, because continuing could skip elements or read garbage. **Not every position throws.** Change the test to `"b"`, the second-to-last element, and the loop ends silently with `[a, c]`: `ArrayList`'s `hasNext()` is only `cursor != size` and runs no check, so it returns false before `next()` can look, and `"c"` is never visited. That is a missed element, not a safe removal. ## How the iterator notices (the mechanism) Most JDK collections keep an internal counter, **`modCount`** (modification count), incremented on every structural change. When you create an iterator it snapshots that value into `expectedModCount`. On each `next()` (and `remove()`) the iterator runs a check, `checkForComodification()` in `ArrayList`: if `modCount != expectedModCount`, the collection changed behind its back, so it throws CME. This is called a **fail-fast** iterator: it fails at its next check, loudly, rather than carrying on and producing wrong results. ## Why fail fast at all? If the iterator quietly kept going after a removal, it could skip the element right after the removed one, or index past the end. Surfacing a clear exception at the loop's next step, close to the misuse, is far better than a subtle, data-dependent bug. CME is a **bug detector**, not a feature you should catch and ignore. ## The correct fixes 1. **`Iterator.remove()`** — the iterator's own remove keeps `expectedModCount` in sync: ```java Iterator<String> it = list.iterator(); while (it.hasNext()) { if (it.next().equals("b")) it.remove(); } ``` 2. **`Collection.removeIf(predicate)`** (Java 8+) — concise and safe as a replacement for the loop. Called inside a for-each over the same list, it is one more outside modification: if it removes something, the next `next()` throws, provided the loop reaches one. 3. **Iterate a copy, modify the original:** `for (String s : new ArrayList<>(list)) { ... }`. 4. **Collect then modify:** gather the to-remove items in a separate list, then `removeAll`. ## The 'Concurrent' in the name is misleading The same exception *can* fire when one thread iterates while another structurally modifies the collection — but fail-fast detection is **best-effort and not guaranteed** for true concurrency (the `modCount` read isn't synchronized). So you must never *rely* on CME for thread-safety; for genuine multi-threaded access use the concurrent collections (`ConcurrentHashMap` with its **weakly consistent** iterators, `CopyOnWriteArrayList` with its **snapshot** iterators), whose iterators never throw CME. ## CME with no iterator in sight Iterators are the classic source, not the only one: the exception's contract covers any method that detects a modification it does not permit. `HashMap.computeIfAbsent`, `computeIfPresent`, `compute` and `merge` throw it on a best-effort basis when the function you pass modifies the map, and `TreeMap` does the same since JDK 15. `ArrayList.removeIf` throws it when the predicate structurally modifies the list. All of this holds on both JDK 25 and JDK 27.

  • Does calling list.set(i, value) inside a for-each loop throw CME?
    No. set() only replaces an existing element's value, which ArrayList's Javadoc says is not a structural modification, so it does not bump modCount. (Note: for-each gives you no index, so set is awkward there anyway; the point is set() itself is CME-safe.)
  • Is CME a checked or unchecked exception?
    Unchecked — it extends RuntimeException, so you are not required to declare or catch it. Its Javadoc says it should be used only to detect bugs, not as something a correct program depends on.

Like counting people in a room from a clipboard list: if someone walks out (or in) mid-count, your tally is now wrong, so you stop and raise your hand rather than report a bad number.

  • Thinking CME only happens with multiple threads — it's usually a single-threaded for-each bug.
  • Believing list.set() during iteration causes CME — it doesn't, because it isn't a structural modification.
  • Catching CME and ignoring/retrying instead of fixing the modify-while-iterating code.
  • Assuming the JVM guarantees CME on every concurrent modification — detection is best-effort only.

ConcurrentModificationException
Java 1.2
Collection.removeIf
Java 1.8

Assumes JDK 27; JDK 25 LTS behaves the same. Collection.removeIf arrived in 1.8. TreeMap's compute and merge methods throw this exception since JDK 15.

context

open as a page

What is the Iterator interface in Java, and what are its core methods?

level: juniorimportance: must knowfreq 75%

basics

~20 s

Iterator is an object that walks through a collection one element at a time. You call hasNext() to check if more elements remain, next() to get the next one, and remove() to delete the last element returned.

open as a page

How does a fail-fast iterator in java.util, such as ArrayList's, detect concurrent modification internally?

level: middleimportance: must knowfreq 62%

basics

~20 s

The collection keeps a counter called modCount that goes up every time you add or remove an element. When you make an iterator, it remembers that number. On each next() it compares them; if they differ, the collection changed behind its back, so it throws.

open as a page

You need to remove elements from a List while iterating it. What are the correct ways, and what are the pitfalls of each?

level: middleimportance: must knowfreq 70%

basics

~20 s

Don't call list.remove() inside a for-each loop: it usually throws ConcurrentModificationException and can silently skip an element. Use removeIf() with a condition, or an explicit Iterator and iterator.remove(). Looping over a copy and removing from the original also works.

open as a page

How do you safely remove elements from a collection while iterating over it, and why is collection.remove() inside a loop dangerous?

level: middleimportance: must knowfreq 80%

basics

~10 s

Use the iterator's own remove() method, not the collection's. Calling list.remove() while looping with a for-each usually throws ConcurrentModificationException because the collection changed behind the iterator's back.

open as a page

What does ListIterator add over a plain Iterator, and when would you use it?

level: middleimportance: should knowfreq 60%

basics

~20 s

ListIterator works on lists and can move both directions (hasNext/next and hasPrevious/previous). It can also add() new elements and set() (replace) the last one returned during traversal, and it tells you the index via nextIndex()/previousIndex().

open as a page

How does Java's Iterator differ from the older Enumeration, and where does Enumeration still surface in the JDK?

level: middleimportance: should knowfreq 47%

basics

~20 s

Iterator took Enumeration's place in Java 1.2, adding an optional remove() and shorter names, hasNext and next. Enumeration survives in Vector, Hashtable, ClassLoader.getResources, ZipFile.entries and SequenceInputStream. Fail-fast is each class's choice, not an interface difference.

open as a page

What is the relationship between Spliterator, Collection.spliterator(), Stream, and StreamSupport?

level: middleimportance: should knowfreq 40%

basics

~20 s

A Spliterator is the low-level thing that walks (and can split) the elements of a source. Every Collection can make one via spliterator(), and the default stream() and parallelStream() are built on top of it. StreamSupport.stream(...) is the helper that turns any Spliterator into a Stream.

open as a page

What is a Spliterator in Java, and how does it differ from a classic Iterator?

level: middleimportance: should knowfreq 55%

basics

~20 s

A Spliterator walks over the elements of a source (like a list) one at a time, and can also split some of them off into a second Spliterator so the parts can run in parallel. An Iterator can only walk forward, never split.

open as a page

How do fail-fast iterators differ from fail-safe (weakly consistent or snapshot) iterators in Java, and which collections use each?

level: seniorimportance: should knowfreq 58%

basics

~20 s

Fail-fast iterators (ArrayList, HashMap) throw ConcurrentModificationException, best effort, when the collection is structurally modified mid-loop. Fail-safe ones (CopyOnWriteArrayList, ConcurrentHashMap) never throw it: they walk a snapshot or tolerate changes, and may miss the latest updates.

open as a page

What happens when you call Iterator.remove() on a fail-fast, a weakly consistent and a snapshot iterator in Java, with examples of each?

level: seniorimportance: should knowfreq 55%

basics

~10 s

Iterator.remove() works on fail-fast iterators (ArrayList, HashMap) and keeps them in sync. It also works on weakly consistent ones (ConcurrentHashMap), with no ConcurrentModificationException. Snapshot iterators (CopyOnWriteArrayList) refuse it with UnsupportedOperationException.

open as a page

What are Spliterator characteristics, and how does the Streams API use flags like ORDERED, SIZED, DISTINCT, SORTED, and IMMUTABLE?

level: seniorimportance: should knowfreq 45%

basics

~20 s

Characteristics are flags a Spliterator reports about its data: the elements are ordered, the exact count is known, all are unique, or the source can't change. The stream pipeline reads several of them to skip unnecessary work.

open as a page

How does Spliterator.trySplit() work, and what makes a good split for parallel streams?

level: seniorimportance: should knowfreq 48%

basics

~20 s

trySplit() tries to hand off some of the remaining elements, ideally half, to a brand-new Spliterator and keeps the rest for itself, so two threads can work on the two parts at once. If it can't usefully split, it returns null.

open as a page

How would you make your own class iterable with the for-each loop, and what do Iterable and Iterator require of it?

level: seniorimportance: nice to knowfreq 45%

basics

~10 s

Implement the Iterable<T> interface and provide an iterator() method that returns an Iterator<T>. The iterator needs hasNext() and next() (and optionally remove()). Then your object works in a for-each loop.

open as a page

Why did the Java library designers make most collections fail-fast rather than fail-safe, and when does that decision break down?

level: principalimportance: nice to knowfreq 30%

basics

~20 s

The docs state no motive; the usual reading is that single-threaded use is the common case, so iteration stays cheap and misuse usually fails loudly at the next check. It breaks down when collections are shared across threads, where concurrent collections fit instead.

open as a page

How would you write a custom Spliterator, and when is doing so actually worth it?

level: principalimportance: nice to knowfreq 28%

basics

~20 s

You implement tryAdvance (process one element), trySplit (hand off some elements, ideally half, for parallelism), estimateSize (how many are left) and characteristics (the flags). You only bother when you have a custom data source that the built-in Collection/Stream tools can't traverse or parallelize well.

open as a page