Java ConcurrentModificationException
Example
Add an item to a list inside a for-each loop, and catch the exception:
import java.util.ArrayList;
import java.util.ConcurrentModificationException;
public class Main {
public static void main(String[] args) {
ArrayList<String> cars = new ArrayList<String>();
cars.add("Volvo");
cars.add("BMW");
try {
for (String car : cars) {
cars.add("Ford");
}
} catch (ConcurrentModificationException e) {
System.out.println("Error: the list was changed inside the loop.");
}
}
}
Definition and Usage
A ConcurrentModificationException happens when a collection, like an ArrayList, is changed while you loop through it, for example when you add or remove items inside a for-each loop.
To remove items while you loop, use an Iterator and its remove() method, or use the removeIf() method of the list.
Tip: Read more about how to remove items safely in our Java Iterator Tutorial.
Related Pages
Java Exceptions (try...catch) Tutorial
❮ Errors & Exceptions