Runtime Error
java.util.ConcurrentModificationException: Cannot modify a Collection while it is being iterated over
What This Error Means
This error occurs when a program attempts to modify a collection (like a list or set) while it is being iterated over by a loop or an iterator.
Why It Happens
This error typically happens when a program is iterating over a collection and at the same time, another part of the program is trying to modify the same collection. This can happen when using multi-threading or when using methods like remove(), add(), or clear() on the collection while it's being iterated over.
How to Fix It
- 1To fix this error, you can use the following methods: 1) Use a synchronized or thread-safe collection like CopyOnWriteArrayList. 2) Avoid modifying the collection while iterating over it by creating a temporary copy of the collection. 3) Use a for-each loop instead of an iterator if you're using Java 5 or later. 4) Use the Iterator's remove() method to remove elements from the collection while iterating over it.
Example Code Solution
import java.util.ArrayList;
import java.util.Iterator;
class Example {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<String>();
list.add("A");
list.add("B");
list.add("C");
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
list.remove(0); // This will cause the ConcurrentModificationException
}
}
}import java.util.ArrayList;
import java.util.Iterator;
class Example {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<String>();
list.add("A");
list.add("B");
list.add("C");
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
iterator.remove(); // Using the Iterator's remove() method
}
}
}Fix for java.util.ConcurrentModificationException: Cannot modify a Collection while it is being iterated over
Browse Related Clusters
Related JAVA Errors
ORA-12545: TNS:Cannot register with TSLS (TNS Listener Service)
Error executing SQL query: Cannot insert explicit value for identity c
java.lang.StackOverflowError at com.example.Main.main(Main.java:15) -
Could not initialize Bean Validation provider for the constraint annot
Related JAVA Blog Articles
Have a different error? Get an instant explanation.
Explain Another Error