2010-01-13 14 views
0

我需要做這樣的事情...如何對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]); 
} 
+0

可能重複的[Java:高效等同於刪除while迭代集合](http://stackoverflow.com/questions/223918/java-efficient-equivalent-to-removing-while-iterating-a-collection) – McDowell 2011-05-09 12:16:50

回答

6

你可以用iterator.remove()

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

請注意,這可能會導致某些數據類型的運行時間爲O(n^2)(例如, ArrayList)。在這種特殊情況下,在迭代之後簡單地清除集合可能更有效。

+0

以及即時通訊實際上使用命令模式,所以我不能使用迭代器刪除。 – ctrlShiftBryan 2010-01-13 03:35:01

+0

哦,謝謝!我也可以只是重寫這個。 :)你讓我在正確的道路上感謝 – ctrlShiftBryan 2010-01-13 03:36:20

+2

或迭代你的集合。 – 2010-01-13 03:42:53

0

一個側面警告,原始集合的類型在這種情況下也很重要。例如,Arrays.asList(new Integer[]{1, 2, 3});奇怪地創建了一個UnmodifiableList,在這種情況下,您需要實例化一個空的ArrayList執行newList.addAll(Arrays.asList(new Integer[]{1, 2, 3});

相關問題