What happens if you modify an ArrayList while iterating over it, and how do you handle it correctly?
answer
- Fail-fast iterator tracks modCount vs expectedModCount
- Structural change outside iterator -> CME
- Name misleads: fires single-threaded too
- set() is non-structural -> safe
- Fix: Iterator.remove / removeIf / iterate copy / CopyOnWriteArrayList
basics
~10 sChanging an ArrayList's size while looping over it with its iterator usually throws ConcurrentModificationException. To remove during iteration, use the iterator's own remove() method, or skip the loop and use removeIf.
solid answer
~50 sArrayList iterators are fail-fast: each one remembers the list's modCount, which goes up on every structural modification (anything that adds or deletes elements or explicitly resizes the backing array; OpenJDK's sort and replaceAll bump it too). If the list is changed that way through anything other than the iterator itself during iteration, the next next()/remove() detects the mismatch and throws ConcurrentModificationException (CME). This is a best-effort bug-detection mechanism, not a thread-safety guarantee, and despite the name it commonly fires from single-threaded mistakes like removing inside a for-each loop. Correct approaches: use Iterator.remove(), which re-syncs the iterator's expected count; or replace the loop with collection.removeIf(predicate) for bulk conditional removal; or iterate over a copy; or in concurrent scenarios use CopyOnWriteArrayList, whose iterator reads a snapshot and never throws CME. Note set(i, v) is not a structural modification, so it does not trip fail-fast.
code
java · 13 linesList<String> list = new ArrayList<>(List.of("x1", "keep", "x2"));
// Compiles, then throws ConcurrentModificationException at runtime:
// for (String s : list) { if (s.startsWith("x")) list.remove(s); }
// RIGHT 1: iterator's own remove()
Iterator<String> it = list.iterator();
while (it.hasNext()) {
if (it.next().startsWith("x")) it.remove();
}
// RIGHT 2: removeIf (preferred, O(n) overall)
// list.removeIf(s -> s.startsWith("x"));go deeper
Knows that removing from a list while looping over it usually throws an exception and that the iterator's remove or removeIf is the fix.
Explains modCount/expectedModCount, that fail-fast can fire single-threaded, structural vs non-structural ops, and the correct removal patterns.
Frames fail-fast as a best-effort bug detector (not a guarantee), and chooses CopyOnWriteArrayList vs removeIf vs synchronized list per concurrency needs.
Sets coding standards around safe mutation-during-iteration, reasons about weakly-consistent vs fail-fast iterators across collections, and the concurrency/memory trade-offs of copy-on-write.
## The trap A very common bug: ```java for (String s : list) { // for-each uses list.iterator() if (s.startsWith("x")) { list.remove(s); // structural change behind the iterator's back } } ``` This typically throws **ConcurrentModificationException (CME)** — even in a single thread, even with no concurrency at all. The name is misleading. ## How fail-fast works: modCount ArrayList keeps an internal counter, **`modCount`**, incremented on every **structural modification**, which its Javadoc defines as any operation that adds or deletes one or more elements, or explicitly resizes the backing array. When you create an iterator (which a for-each does implicitly), it snapshots `modCount` into `expectedModCount`. On each `next()` (and `remove()`), the iterator runs `checkForComodification()`: if `modCount != expectedModCount`, it throws CME immediately. When you called `list.remove(s)` directly, `modCount` went up but the iterator's `expectedModCount` did not — mismatch → CME on the next loop step. ## 'Fail-fast' is a bug-detector, not a contract Fail-fast iterators throw on a **best-effort** basis to surface bugs early. The docs say it would be wrong to write a program that depends on CME for its correctness. It can miss in unsynchronized concurrent use, and it misses in a single thread too: `hasNext()` only tests `cursor != size`, so one removal while the loop is **on the second-to-last position** ends the loop silently instead of throwing, which can leave the last element unvisited. Treat a CME as 'you have a bug in how you mutate during iteration,' not as a feature to catch. ## Structural vs non-structural - **Structural** (bumps modCount, can trip fail-fast): `add`, `remove`, `clear`, and also `trimToSize` and `ensureCapacity` when it grows the array, neither of which changes the size. - **Also bump modCount in OpenJDK**: `sort` and `replaceAll`, so calling them inside a for-each trips CME on the next step though the size stays the same. - **Non-structural** (no modCount bump, safe during iteration): `set(i, value)` replaces an element in place. So updating values with `set` while iterating is fine; adding/removing is not. ## The correct ways 1. **Iterator.remove()** — the iterator updates `expectedModCount` in lockstep, so no CME: ```java Iterator<String> it = list.iterator(); while (it.hasNext()) { if (it.next().startsWith("x")) it.remove(); // safe } ``` 2. **removeIf(predicate)**, called instead of a loop — cleanest for conditional bulk removal; O(n) overall, and no CME unless the predicate itself modifies the list: ```java list.removeIf(s -> s.startsWith("x")); ``` 3. **Iterate a copy** — loop over `new ArrayList<>(list)` and mutate the original. 4. **Collect-then-remove** — gather matches in a second list, then `removeAll`. 5. **Concurrency** — use **CopyOnWriteArrayList**: its iterator works on an immutable snapshot taken at creation, so concurrent writes never cause CME (writes copy the whole array; great for read-heavy, write-rare data). ## Why not just catch the exception? Catching CME and continuing is wrong: the same iterator keeps throwing, because its `expectedModCount` stays stale, and restarting the loop reprocesses elements. Fix the mutation pattern instead.
- Does CopyOnWriteArrayList throw ConcurrentModificationException?No. Its iterator operates on an immutable snapshot of the array taken when the iterator was created, so concurrent modifications are invisible to it and it never throws CME (but the iterator won't see later writes).
- Is calling list.set(i, v) inside a for-each loop safe?Yes. set only replaces an element, so it is not a structural modification, does not bump modCount, and does not trigger fail-fast.
- Removing/adding via the collection inside a for-each loop
- Thinking CME only happens with multiple threads
- Catching CME and continuing the loop
- Believing set(i,v) trips fail-fast (it is not a structural modification)
- Relying on CME as a correctness guarantee rather than a bug detector
- Assuming only a size change bumps modCount (sort and trimToSize do too)
- Collection.removeIf
- Java 1.8
context
- ArrayList (Java SE 27 & JDK 27)docs.oracle.com
- CopyOnWriteArrayList (Java SE 27 & JDK 27)docs.oracle.com
- ArrayList.java at jdk-27-gagithub.com