迭代通过集合,避免ConcurrentModificationException在循环中删除 [英] Iterating through a Collection, avoiding ConcurrentModificationException when removing in loop
问题描述
我们都知道你不能这样做:
We all know you can't do this:
for (Object i : l) {
if (condition(i)) {
l.remove(i);
}
}
ConcurrentModificationException
等...这显然工作有时,但不总是。下面是一些具体代码:
ConcurrentModificationException
etc... this apparently works sometimes, but not always. Here's some specific code:
public static void main(String[] args) {
Collection<Integer> l = new ArrayList<Integer>();
for (int i=0; i < 10; ++i) {
l.add(new Integer(4));
l.add(new Integer(5));
l.add(new Integer(6));
}
for (Integer i : l) {
if (i.intValue() == 5) {
l.remove(i);
}
}
System.out.println(l);
}
这当然会导致:
Exception in thread "main" java.util.ConcurrentModificationException
b $ b
...即使多个线程没有这样做...无论如何。
... even though multiple threads aren't doing it... Anyway.
这个问题的最佳解决方案是什么?如何从循环中的集合中删除项目,而不抛出此异常?
What's the best solution to this problem? How can I remove an item from the collection in a loop without throwing this exception?
我也使用任意的集合
这里,不一定是 ArrayList
,所以你不能依赖 get
。
I'm also using an arbitrary Collection
here, not necessarily an ArrayList
, so you can't rely on get
.
推荐答案
Iterator.remove()
是安全的,你可以这样使用: p>
Iterator.remove()
is safe, you can use it like this:
List<String> list = new ArrayList<>();
// This is a clever way to create the iterator and call iterator.hasNext() like
// you would do in a while-loop. It would be the same as doing:
// Iterator<String> iterator = list.iterator();
// while (iterator.hasNext()) {
for (Iterator<String> iterator = list.iterator(); iterator.hasNext();) {
String string = iterator.next();
if (string.isEmpty()) {
// Remove the current element from the iterator and the list.
iterator.remove();
}
}
注意 Iterator.remove
是在迭代期间修改集合的唯一安全方法;
Note that Iterator.remove
is the only safe way to modify a collection during iteration; the behavior is unspecified if the underlying collection is modified in any other way while the iteration is in progress.
来源:
http://docs.oracle.com/javase/tutorial /collections/interfaces/collection.html
同样,如果您有 ListIterator
,并且想要添加项目,您可以使用 ListIterator#add
,出于同样的原因,您可以使用 Iterator#remove
—它的设计允许它。
And similarly, if you have a ListIterator
and want to add items, you can use ListIterator#add
, for the same reason you can use Iterator#remove
— it's designed to allow it.
这篇关于迭代通过集合,避免ConcurrentModificationException在循环中删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!