如何迭代Collection <t>并修改其项目而不使用ConcurrentModificationException?</t>

时间:2010-01-13 03:31:06

标签: java iterator collections concurrentmodification

我需要做这样的事情......

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


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

显然这会引发ConcurrentModificationException ...

所以我尝试了这个但看起来并不优雅/高效并抛出了Type安全:从Object到T的未经检查的强制转换警告

Object[] list = myCollection.toArray();
for(int index = list.length - 1; index >= 0; index--) {
 myCollection.remove((T)list[index]);
}

2 个答案:

答案 0 :(得分:6)

您可以使用iterator.remove()

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

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

答案 1 :(得分:0)

另一方面,原始集合的类型在这种情况下也很重要。例如,Arrays.asList(new Integer[]{1, 2, 3});奇怪地创建了一个UnmodifiableList,在这种情况下,您需要实例化一个空的ArrayList执行newList.addAll(Arrays.asList(new Integer[]{1, 2, 3});