Why does this code throw ConcurrentModificationException?
List<Integer> nums = new ArrayList<>(List.of(1, 2, 3, 4));
for (Integer n : nums) {
if (n % 2 == 0) nums.remove(n);
}Options
removeis not allowed on lists created withnew ArrayList- The list was modified while the for-each iterator was walking it (Correct option)
Integerobjects cannot be removed from a list- Another thread is changing the list at the same time
Answer
Because the list was structurally modified while the for-each iterator was walking it
Why
The for-each loop uses an iterator behind the scenes. The iterator remembers how many modifications the list had when it started. If you add or remove through the list itself during the loop, the iterator notices the count changed and fails fast with this exception. It happens even with a single thread.
Safe options: nums.removeIf(n -> n % 2 == 0), use iterator.remove(), or build a new list with a stream.
nums.removeIf(n -> n % 2 == 0);Remember
Do not modify a collection while iterating it; use removeIf or Iterator.remove.