【问题标题】:How do you interate over a Collection<T> and modify its items without ConcurrentModificationException?如何在没有 ConcurrentModificationException 的情况下遍历 Collection<T> 并修改其项目?
【发布时间】:2011-01-04 11:32:52
【问题描述】:

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

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


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

显然这会引发 ConcurrentModificationException...

所以我已经尝试过了,但它看起来并不优雅/高效,并且会引发类型安全:Unchecked cast from Object to T 警告

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

【问题讨论】:

标签: java iterator collections concurrentmodification


【解决方案1】:

你可以使用iterator.remove():

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

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

【讨论】:

  • 好吧,我实际上使用的是命令模式,所以我不能使用迭代器删除。
  • 哦,谢谢!我也可以忽略它。 :) 你让我走上正确的道路谢谢
  • 或在迭代时复制集合。
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-22
    • 2021-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多