Collections: modifying during a for-each throws

The iterator detects structural changes and fails fast. This is a feature - it stops you reading a corrupted sequence.

Code
var list = new ArrayList<>(List.of("a", "b", "c"));
try {
    for (String s : list) {
        if (s.equals("b")) list.remove(s);
    }
} catch (ConcurrentModificationException e) {
    System.out.println("ConcurrentModificationException as expected");
}

var it = list.iterator();
while (it.hasNext()) {
    if (it.next().equals("b")) it.remove();
}
System.out.println("Iterator.remove is the safe way: " + list);
Output
Iterator.remove is the safe way: [a, c]
Advertisement

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-07-30