Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 所有集合成员的调用删除方法_Java_Iterator_Set_Hashset_Elements - Fatal编程技术网

Java 所有集合成员的调用删除方法

Java 所有集合成员的调用删除方法,java,iterator,set,hashset,elements,Java,Iterator,Set,Hashset,Elements,在程序中,我有一个HashSet的Foo: 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); } } final Set=new

在程序中,我有一个
HashSet
Foo

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);
  }
}
final Set=new HashSet();
//向集合中添加许多元素
福班{
公共空间销毁(){
//其他内容[例如将其作为事件处理程序删除]
设置。移除(此);
}
}
我想为集合中的所有成员调用
destroy()

destroy()
方法的目的是将元素作为事件处理程序从集合中删除

这就是我尝试过的:

  • 对每个循环使用迭代器/抛出ConcurrentModificationException:

    for(迭代器i=set.Iterator();i.hasNext();){i.next().destroy()}

  • 一次拆下一个元件-请执行以下操作:

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


我正在寻找一个解决这个问题的方法,它可以很好地处理集合中的很多元素。非常感谢。

您的第一次尝试就快完成了

试一试

for(迭代器i=set.Iterator();i.hasNext();){
Foo-Foo=i.next();
//其他关于foo的东西,比如foo.someOtherStuff();
i、 删除();
}

这将安全地从集合中移除。甚至不需要调用destroy。

可以设置.clear();帮助你吗?@BrunoFranco这很有帮助,但是做其他事情怎么样尝试在类中实现/重写finalize(),在finalize中,您可以处理//做其他事情-阅读有关如何正确重写finalize方法java.lang.Object的教程,并且需要调用它。
   for (Iterator<Foo> i = set.iterator(); i.hasNext(); ) {
        Foo foo = i.next();  
        // other stuff with foo. Something like foo.someOtherStuff();
        i.remove();
   }