【问题标题】:How to avoid ConcurrentModificationException while iterating through a list遍历列表时如何避免 ConcurrentModificationException
【发布时间】:2017-05-30 00:56:56
【问题描述】:

我有一个 Country 类,它保存一个由 Human 对象组成的列表。在 Country 类中,我具有以下功能;

public void processOneDay(int day, List<Country> countryList, int numberOfCountries ){
        ListIterator<Human> iter = people.listIterator();
        while(iter.hasNext()){
            Human h = iter.next();
            h.move(day, countryList, numberOfCountries);
        }
    }

Human 类的 move() 方法负责将人类从一个国家移动到另一个国家,但此方法将该人从源国家的人员列表中删除并将其添加到目的地国家的人员列表中。因此,在迭代时执行此操作会导致我出现 ConcurrentModificationException。我尝试使用迭代器本身的删除功能,但我把事情搞砸了。那么,我该如何处理这种情况?

【问题讨论】:

    标签: arraylist iterator concurrentmodification


    【解决方案1】:

    只需复制列表,您可以使用此列表进行迭代。

    List&lt;Human&gt; copy = new ArrayList&lt;Human&gt;(people);

    【讨论】:

      【解决方案2】:

      正如您所发现的,您无法修改正在迭代的列表,因此有两种选择,您需要遍历列表的副本,或者您需要使用 for 循环遍历列表,并且直接索引列表中的项目。

      复制列表更容易编写,但如果列表很大,则会浪费大量 CPU 周期和内存。使用for (var i = 0; i &lt; list.Count; i++) list[i] 有点复杂但效率更高。请注意,如果您从列表中删除项目,则无需增加 i

      【讨论】:

        猜你喜欢
        • 2011-05-03
        • 2017-10-19
        • 2010-09-18
        相关资源
        最近更新 更多