如何在没有ConcurrentModificationException的情况下对Collection <T>进行交互并修改其项目?

ctr*_*yan 0 java collections iterator concurrentmodification

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

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


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

显然这会引发ConcurrentModificationException ...

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

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

not*_*oop 6

你可以使用iterator.remove():

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

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

  • 或者在迭代时复制集合. (2认同)