java.util.ConcurrentModificationException is thrown in collections,when one thread is iterating a collection and at the same time another thread is modifying it.This is also applicable to collection accessed by a single thread as well when it is being iterated and modified at the same time.Consider the below code where the arraylist is iterated by the for loop and being modified at the same time.
when we try to run the above code,we will get the below exception
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.AbstractList$Itr.checkForComodification(Unknown Source)
at java.util.AbstractList$Itr.next(Unknown Source)
at COM.Test.main(Test.java:17)
To avoid this exception,iterate the collection using the ListIterator and for adding the object to the list use the add method of the ListIterator.Sample code is shown below:
When we run the above program,we will get the below output
Elements:[one, ONE, two, TWO, three, THREE]
public class Test { public static void main(String[] args) { list.add("one"); list.add("two"); list.add("three"); for(String var:list) //Iterate the ArrayList { list.add(var.toUpperCase); //Add the new String to ArrayList } } } |
when we try to run the above code,we will get the below exception
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.AbstractList$Itr.checkForComodification(Unknown Source)
at java.util.AbstractList$Itr.next(Unknown Source)
at COM.Test.main(Test.java:17)
To avoid this exception,iterate the collection using the ListIterator and for adding the object to the list use the add method of the ListIterator.Sample code is shown below:
public class Test { public static void main(String[] args) { list.add("one"); list.add("two"); list.add("three"); ListIterator<String> itr=list.listIterator(); while(itr.hasNext()) { itr.add(itr.next().toUpperCase()); } System.out.println("Elements:"+list); } |
When we run the above program,we will get the below output
Elements:[one, ONE, two, TWO, three, THREE]