我需要做這樣的事情...如何對Collection <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的...
所以我已經試過,但並不似乎優雅/有效,並拋出一個類型安全:未選中投從Object至T警告
Object[] list = myCollection.toArray();
for(int index = list.length - 1; index >= 0; index--) {
myCollection.remove((T)list[index]);
}
可能重複的[Java:高效等同於刪除while迭代集合](http://stackoverflow.com/questions/223918/java-efficient-equivalent-to-removing-while-iterating-a-collection) – McDowell 2011-05-09 12:16:50