Reputation: 2264
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:
Use an Iterator / for each loop - throws ConcurrentModificationException
:
for (Iterator<Foo> i = set.iterator(); i.hasNext(); ) { i.next().destroy() }
Remove one element at the time - horrible inefficient:
while (!set.isEmpty()) { set.iterator().next().destory(); }
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
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