在列表迭代期间从 java.util.List 中删除元素时是否抛出 ConcurrentModificationException?

问题描述:

@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);
}

当我运行这段代码时,我会抛出一个ConcurrentModificationException.

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

看起来好像当我从 list 中删除指定的元素时,list 不知道它的 size 已更改.

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

我想知道这是否是 collections 和删除元素的常见问题?

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

我相信这就是 Iterator.remove() 方法,以便能够在迭代时从集合中删除元素.

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

例如:

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