Search code examples
javalistconcurrentmodification

Getting a ConcurrentModificationException thrown when removing an element from a java.util.List during list iteration?


@Test
public void testListCur(){
    List<String> li=new ArrayList<String>();
    for(int i=0;i<10;i++){
        li.add("str"+i);
    }

    for(String st:li){
        if(st.equalsIgnoreCase("str3"))
            li.remove("str3");
    }
    System.out.println(li);
}

When I run this code,I will throw a ConcurrentModificationException.

It looks as though when I remove the specified element from the list, the list does not know its size have been changed.

I'm wondering if this is a common problem with collections and removing elements?


Solution

  • I believe this is the purpose behind the Iterator.remove() method, to be able to remove an element from the collection while iterating.

    For example:

    Iterator<String> iter = li.iterator();
    while(iter.hasNext()){
        if(iter.next().equalsIgnoreCase("str3"))
            iter.remove();
    }