如何避免java.util.ConcurrentModificationException通过从一个ArrayList的删除元素进行遍历时, [英] How to avoid java.util.ConcurrentModificationException when iterating through an removing elements from an ArrayList
问题描述
我有,我想遍历它的ArrayList。在遍历它,我必须删除在同一时间的元素。显然,这将引发 java.util.ConcurrentModificationException
。
I have an ArrayList that I want to iterate over it. 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?
我删除的元素不是在循环本身,而是code的另一部分。
I remove the elements not in the loop itself but another part of the code.
我的code是这样的:
My code looks like this:
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();
a.doSomething might call Test.removeA();
推荐答案
有两种选择:
- 创建要删除值的列表,的添加应用于循环内的列表中,然后调用
originalList.removeAll(valuesToRemove)
在结束 - 使用
删除()
的迭代器本身的方法。请注意,这意味着你不能使用增强的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();
}
}
这篇关于如何避免java.util.ConcurrentModificationException通过从一个ArrayList的删除元素进行遍历时,的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!