Getting “ConcurrentModificationException” while removing elements from ArrayList

1.08K views
0

I’m trying to remove elements from an ArrayList while iterating like code given below:

for (String str : myArrayList) {
if (someCondition) {
myArrayList.remove(str);
}
}

I got ConcurrentModificationException when trying to remove element from the list at the same time when iterating myArrayList.

Is there any solution to solve this problem?

Answered question
0

You can’t remove or add (modify collection) value from Array List (any collection) while iterating it. You will get below error.

Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:901)
at java.util.ArrayList$Itr.next(ArrayList.java:851)
at HelloWorld.main(HelloWorld.java:13)

If you modify your collection (List) it will try to re-index the elements and at the same time its already in for loop, hence it will throw ConcurrentModificationException. Use Iterator, iterator take the copy of your collection.

Example :

Iterator<String> it = myArrayList.iterator();
while (it.hasNext()) {
String value = it.next();
System.out.println("List Value:" + value);
if (someCondition) {
myList.remove("value );

}
}

Answered question