When Exception in thread "main" java.util.ConcurrentModificationException occurs.

package com.ekiras.demo;

import java.util.ArrayList;
import java.util.List;

public class Test {

public static void main(String args[]){

// create a new list
List<String> list = new ArrayList<String>();

// add 50 items to the list
for(int itr=0;itr<50;itr++)
list.add("user-"+(itr+1));

// try to remove item from list while iterating the list
for(String str : list){
if(str.equals("user-15")){
list.remove(str);
}
}
}

}

The above code will give the following error.
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 testing.Test.main(Test.java:18)

How to avoid ConcurrentModificationException


  • Create the list of type CopyOnWriteArrayList, this will create a new copy of list for every operation performed and then replace it with original.
    List<String> list = new CopyOnWriteArrayList<String>();
  • Create a new copy of the list for iterating the list
    for(String str : new ArrayList<String>(list))
  • Use the Iterator to iterate the list and modify its contents.
    Iterator<String> iterator = list.iterator();
    while(iterator.hasNext()){
    String str = iterator.next();
    if(str.equals("user-15")){
    iterator.remove();
    }
    }