为什么在ArrayList中出现ConcurrentModificationException? [英] Why ConcurrentModificationException in ArrayList?

查看:70
本文介绍了为什么在ArrayList中出现ConcurrentModificationException?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么以下代码引发ConcurrentModificationException? Josh Bloch可以避免ConcurrentModificationException。

why following code throwing ConcurrentModificationException? Josh Bloch can avoid ConcurrentModificationException.

ArrayList<Integer> list=new ArrayList<Integer>();
list.add(100);
list.add(200);
list.add(300);
list.add(400);
for(Integer field : list) {    
    list.remove(field);
    list.add(200);
}       


推荐答案

您不能使用remove在列表上,同时使用 for each循环。相反,您可以使用此方法在迭代器上调用remove:

You can't use remove on the list while using the "for each" loop. Instead, you can use this to call remove on the iterator:

Iterator<Integer> iterator = list.iterator();
while(iterator.hasNext()) {
    Integer integer = iterator.next();

    // ...check if you want to remove this one...

    iterator.remove();
}

如果您确实想将每个值都替换为 200,或替换为其他一些值,则建立一个新列表可能更有意义:

If you actually want to replace every value with "200", or replace with some other value, it might make more sense to build up a new list:

List<Integer> newList = new ArrayList<Integer>();

Iterator<Integer> iterator = list.iterator();
while(iterator.hasNext()) {
    Integer integer = iterator.next();

    newList.add(integer);

    iterator.remove();
}

这篇关于为什么在ArrayList中出现ConcurrentModificationException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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