2014-09-01 40 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(); 
    } 

这将从设定的安全删除。甚至不用打电话破坏。