在列表迭代期间从java.util.List中删除元素时抛出ConcurrentModificationException? [英] Getting a ConcurrentModificationException thrown when removing an element from a java.util.List during list iteration?

查看:128
本文介绍了在列表迭代期间从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();
}

这篇关于在列表迭代期间从java.util.List中删除元素时抛出ConcurrentModificationException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆