2014-09-01 38 views
0

在程序去除方法,我有FooHashSet呼籲所有成員集

final Set<Foo> set = new HashSet<>(); 
// add a lot of elements to the set 

class Foo { 
    public void destroy() { 
    // other stuff [such as removing this as event handler] 
    set.remove(this); 
    } 
} 

我想打電話給destroy()該組的所有成員。

destroy()方法的目的是從元素中移除元素作爲事件的處理函數。

這是我曾嘗試:

  • 使用迭代器/每個循環 - 拋出ConcurrentModificationException

    for (Iterator<Foo> i = set.iterator(); i.hasNext();) { i.next().destroy() }

  • 當時刪除一個元素 - 可怕的效率低下:

    while (!set.isEmpty()) { set.iterator().next().destory(); }

我正在尋找解決這個問題的方法,可以很好地處理很多元素。非常感謝你。

+0

Can set.clear();幫助你? – 2014-09-01 11:50:09

+0

@BrunoFranco這有助於「//做其他事情」嗎? - – 2014-09-01 11:52:11

+0

嘗試在您的類中實現/覆蓋finalize(),並在finalize中處理//執行其他操作 - 閱讀關於如何正確覆蓋finalize方法java java.lang.Object的教程,並且需要調用它。 – Raf 2014-09-01 12:05:21

回答

2

你幾乎完成了你的第一次嘗試。

嘗試

for (Iterator<Foo> i = set.iterator(); i.hasNext();) { 
     Foo foo = i.next(); 
     // other stuff with foo. Something like foo.someOtherStuff(); 
     i.remove(); 
    } 

這將從設定的安全刪除。甚至不用打電話破壞。