Skip to main content

Exception in thread java.util.ConcurrentModificationException

Points To Remember


  • ConcurrentModificationException occurs when the you you try to modify the collection you are using or iterating.
  • It can be prevented if you create a new object of that collection and do operations on that and then assign it back to the original object.

java.util.ConcurrentModificationException

In the following code we will be iterating on the list and trying to remove the null objects from the list.

import java.util.*;
public class Demo {
public static void main(String args[]) {
// create an array of string objs
String init[] = {
"One", "Two", null, null, "One", "Two", null, "Three", "Four", "Two", null
};
// create two lists
List<String> list = new ArrayList(Arrays.asList(init));
for (String str: list) {
if (str == null) list.remove(str);
}
System.out.println("List value: " + list);
}
}

The above code will throw the following Exception
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:859)
at java.util.ArrayList$Itr.next(ArrayList.java:831)
at Demo.main(Demo.java:10)


The reason for this is that you are trying to modify the list you are iterating, or on a broader term  you are trying to modifying a collection you are using.

So to remove this kind of exception can be removed by taking another local list( or any collection you are using) to do operations and then assign it back to the list( or collection).

import java.util.*;
public class Demo {
public static void main(String args[]) {
// create an array of string objs
String init[] = {
"One", "Two", null, null, "One", "Two", null, "Three", "Four", "Two", null
};
// create two lists
List<String> list = new ArrayList(Arrays.asList(init));
List<String> temp = new ArrayList<String>();
for (String str: list) {
if (str != null) temp.add(str);
}
list = temp;
System.out.println("List value: " + list);
}
}

The above code will give the following output

List value: [One, Two, One, Two, Three, Four, Two]


Comments