Frithjof
Frithjof

Reputation: 2264

Call removing method for all set members

In a program, I have a HashSet of 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);
  }
}

I want to call destroy() for all members of the set.

The purpose of the destroy() method is to remove the element as handler for events and from the set.

This is what I have tried:

I am looking for a solution to this problem that works well with very many elements in the set. Thank you very much.

Upvotes: 0

Views: 77

Answers (1)

Suresh Atta
Suresh Atta

Reputation: 122026

You are almost done in your first attempt.

Try

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

That will remove safely from the set. Need not to call destroy even.

Upvotes: 2

Related Questions