在列表迭代期间从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.
看起来当我从列表中删除指定的元素时,列表不知道它的大小是否已被更改。
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?
答
我相信这是背后的目的 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();
}