如何在没有ConcurrentModificationException的情况下对Collection 进行交互并修改其项目?
我需要做这样的事……
Collection myCollection; ///assume it is initialized and filled for(Iterator index = myCollection.iterator(); index.hasNext();) { Object item = index.next(); myCollection.remove(item); }
显然这会抛出ConcurrentModificationException …
所以我尝试了这个但是看起来并不优雅/高效并抛出类型安全:从Object到T的未经检查的强制转换警告
Object[] list = myCollection.toArray(); for(int index = list.length - 1; index >= 0; index--) { myCollection.remove((T)list[index]); }
你可以使用iterator.remove()
:
for(Iterator> index = myCollection.iterator(); index.hasNext();) { Object item = index.next(); index.remove(); }
请注意,这可能会导致某些数据类型(例如ArrayList
)的O(n^2)
运行时。 在这种特殊情况下,在迭代后简单地清除集合可能更有效。
另一方面,原始集合的类型在这种情况下也很重要。 例如, Arrays.asList(new Integer[]{1, 2, 3});
奇怪地创建一个UnmodifiableList
,在这种情况下你需要实例化一个空的ArrayList执行newList.addAll(Arrays.asList(new Integer[]{1, 2, 3});