Skip to main content
Java Bug Hunt Hard +35 XP

ConcurrentModificationException

This crashes when removing items while iterating.

JavaFind the bug
1List<String> items = new ArrayList<>(Arrays.asList("a", "b", "c"));
2for (String item : items) {
3 if (item.equals("b")) {
4 items.remove(item);
5 }
6}
The bug is on line 4

Select the correct fix

Show answer and explanation

Answer: Both A and B are valid fixes

Modifying a collection during enhanced for loop causes ConcurrentModificationException. Use Iterator or removeIf().

Hint: You can't modify a collection while iterating over it.

What this challenge tests

Bug Hunt in Java: collections, iteration, concurrent-modification.

Related challenges