ConcurrentModificationException

ConcurrentModificationException

本文介绍了如何在一个集合< T>并修改其项目没有ConcurrentModificationException?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要这样做...

Collection<T> myCollection; ///assume it is initialized and filled


for(Iterator<?> index = myCollection.iterator(); index.hasNext();)
{
    Object item = index.next();
    myCollection.remove(item);
}

显然这会抛出ConcurrentModificationException ...

Obviously this throws ConcurrentModificationException...

所以我试过了,但不似乎优雅/高效,并引发一个类型安全:从对象到T警告未检查的转换

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[] list = myCollection.toArray();
for(int index = list.length - 1; index >= 0; index--) {
 myCollection.remove((T)list[index]);
}


推荐答案

href =http://java.sun.com/j2se/1.5.0/docs/api/java/util/Iterator.html#remove() =nofollow noreferrer> 迭代器。对于(Iterator<?> index = myCollection),请移除()

You can just use iterator.remove():

for(Iterator<?> index = myCollection.iterator(); index.hasNext();)
{
    Object item = index.next();
    index.remove();
}

请注意,这可能会导致 O )某些数据类型的运行时(例如 ArrayList )。在这种特殊情况下,在迭代后简单清除集合可能更有效。

Beware that this may cause O(n^2) runtime for some datatypes (e.g. ArrayList). In this particular case, it might be more efficient to simply clear the collection after the iteration.

这篇关于如何在一个集合&lt; T&gt;并修改其项目没有ConcurrentModificationException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 16:11