Repaso
Español
Java CoreIntermediateJV-24

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

  1. remove is not allowed on lists created with new ArrayList
  2. The list was modified while the for-each iterator was walking it (Correct option)
  3. Integer objects cannot be removed from a list
  4. 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.

Key terms

Practice this question in Repaso