本文介绍了迭代遍历和从 ArrayList 中删除元素时如何避免 java.util.ConcurrentModificationException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要迭代的 ArrayList.在迭代它时,我必须同时删除元素.显然这会抛出一个 java.util.ConcurrentModificationException.

I have an ArrayList that I want to iterate over. While iterating over it I have to remove elements at the same time. Obviously this throws a java.util.ConcurrentModificationException.

处理这个问题的最佳实践是什么?我应该先克隆列表吗?

What is the best practice to handle this problem? Should I clone the list first?

我删除的元素不在循环本身而是代码的另一部分.

I remove the elements not in the loop itself but another part of the code.

我的代码如下:

public class Test() {
    private ArrayList<A> abc = new ArrayList<A>();

    public void doStuff() {
        for (A a : abc)
        a.doSomething();
    }

    public void removeA(A a) {
        abc.remove(a);
    }
}

a.doSomething 可能会调用 Test.removeA();

推荐答案

两个选项:

  • 创建一个你想要删除的值列表,添加到循环中的那个列表,然后在最后调用originalList.removeAll(valuesToRemove)
  • 在迭代器本身上使用 remove() 方法.请注意,这意味着您不能使用增强的 for 循环.
  • Create a list of values you wish to remove, adding to that list within the loop, then call originalList.removeAll(valuesToRemove) at the end
  • Use the remove() method on the iterator itself. Note that this means you can't use the enhanced for loop.

作为第二个选项的示例,从列表中删除长度大于 5 的任何字符串:

As an example of the second option, removing any strings with a length greater than 5 from a list:

List<String> list = new ArrayList<String>();
...
for (Iterator<String> iterator = list.iterator(); iterator.hasNext(); ) {
    String value = iterator.next();
    if (value.length() > 5) {
        iterator.remove();
    }
}

这篇关于迭代遍历和从 ArrayList 中删除元素时如何避免 java.util.ConcurrentModificationException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-03 21:23