[英]How do you interate over a Collection<T> and modify its items without ConcurrentModificationException?
I need to do something like this... 我需要做这样的事情...
Collection<T> myCollection; ///assume it is initialized and filled
for(Iterator<?> index = myCollection.iterator(); index.hasNext();)
{
Object item = index.next();
myCollection.remove(item);
}
Obviously this throws ConcurrentModificationException... 显然,这引发了ConcurrentModificationException ...
So I have tried this but doesn't does seem elegant/efficient and throws a Type safety: Unchecked cast from Object to T warning 因此,我尝试了这种方法,但似乎并不优雅/高效,并且抛出了类型安全性:未选中,从Object到T的警告
Object[] list = myCollection.toArray();
for(int index = list.length - 1; index >= 0; index--) {
myCollection.remove((T)list[index]);
}
You can just use iterator.remove()
: 您可以只使用
iterator.remove()
:
for(Iterator<?> index = myCollection.iterator(); index.hasNext();)
{
Object item = index.next();
index.remove();
}
Beware that this may cause O(n^2)
runtime for some datatypes (eg ArrayList
). 注意,这可能会导致某些数据类型(例如
ArrayList
)的O(n^2)
运行时。 In this particular case, it might be more efficient to simply clear the collection after the iteration. 在这种特殊情况下,在迭代后简单清除集合可能会更有效。
A side-caveat, the type of the original collection matters in this instance as well. 在这种情况下,侧面凹面也很重要。 For instance,
Arrays.asList(new Integer[]{1, 2, 3});
例如,
Arrays.asList(new Integer[]{1, 2, 3});
strangely creates an UnmodifiableList
, in which case you would need to instantiate an empty ArrayList perform newList.addAll(Arrays.asList(new Integer[]{1, 2, 3});
. 奇怪地创建了一个
UnmodifiableList
,在这种情况下,您将需要实例化一个空的ArrayList,执行newList.addAll(Arrays.asList(new Integer[]{1, 2, 3});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.