Quick Answer
Handle collection modification during iteration.
Understanding the Issue
This exception occurs when a collection is modified while being iterated, except through the iterator's own methods.
The Problem
This code demonstrates the issue:
Java
Error
List<String> list = new ArrayList<>();
list.add("a"); list.add("b");
for (String s : list) {
if (s.equals("a")) list.remove(s); // Throws
}
The Solution
Here's the corrected code:
Java
Fixed
// Solution 1: Use Iterator.remove()
Iterator<String> it = list.iterator();
while (it.hasNext()) {
if (it.next().equals("a")) it.remove();
}
// Solution 2: Java 8 removeIf()
list.removeIf(s -> s.equals("a"));
// Solution 3: Concurrent collections
List<String> safeList = new CopyOnWriteArrayList<>(list);
// Solution 4: Create copy for iteration
for (String s : new ArrayList<>(list)) {
if (s.equals("a")) list.remove(s);
}
Key Takeaways
Never modify collections directly during iteration.