问题描述
我有一个ArrayList,我想迭代。在迭代时,我必须同时删除元素。显然,这会抛出一个 java.util.ConcurrentModificationException
。
处理这个问题的最佳实践是什么?我应该先克隆列表吗?
我删除了不在循环中的元素,而是代码的另一部分。
我的代码如下所示:
public class Test(){
private ArrayList< A> abc = new ArrayList< A>();
$ b $ public void doStuff(){
for(A a:abc)
a.doSomething();
}
public void removeA(A a){
abc.remove(a);
code $
$ b $ a $ doSomething 可能会调用 Test.removeA()
;
解决方案两个选项:
- 创建一个你想删除的值列表, 添加到循环内的列表,然后在最后使用
originalList.removeAll(valuesToRemove)
c $ c>方法迭代器本身。请注意,这意味着您不能使用增强for循环。
作为第二个选项的示例,删除任何字符串长度大于5的列表:
List< String> list = new ArrayList< String>();
...
(Iterator< String> iterator = list.iterator(); iterator.hasNext();){
String value = iterator.next();
if(value.length()> 5){
iterator.remove();
}
}
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.
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
might call Test.removeA()
;
Two options:
- 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.
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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!