Question
What causes ConcurrentModificationException while iterating over a List in Java, and how can I fix it?
List<String> list = new ArrayList<>(Arrays.asList("A", "B", "C"));
for (String item : list) {
if (item.equals("B")) {
list.remove(item); // This line will cause ConcurrentModificationException
}
}
Answer
The ConcurrentModificationException in Java occurs when a collection is modified while iterating over it using an iterator or enhanced for-loop. This exception is a part of the Java Collections Framework and is designed to prevent inconsistent states.
List<String> list = new ArrayList<>(Arrays.asList("A", "B", "C"));
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
String item = iterator.next();
if (item.equals("B")) {
iterator.remove(); // Safe way to remove item
}
}
Causes
- Modifying a list while traversing it using a `for-each` loop or an iterator.
- Using one collection in one thread while modifying it in another thread without proper synchronization.
Solutions
- Use `Iterator.remove()` method while iterating through the collection.
- Use a temporary list to collect items to be removed and delete them after the loop.
- Utilize concurrent collections like `CopyOnWriteArrayList` for thread-safe modifications.
Common Mistakes
Mistake: Using `list.remove(item)` within a for-each loop.
Solution: Use `iterator.remove()` to safely remove items during iteration.
Mistake: Not checking for thread safety when using multiple threads.
Solution: Consider using concurrent collections like `ConcurrentHashMap` or `CopyOnWriteArrayList`.
Helpers
- ConcurrentModificationException
- Java exception handling
- iterating over list in Java
- remove from list in Java