tags:

views:

82

answers:

4

I would like to iterate over a Set and remove the elements from the set that match some condition. The documentation of iterator says nothing about modifying the list while iterating over it.

Is this possible? If not, what would be the best way to do it? Note that I only want to remove elements from the set that are provided by the Iterator.

Edit: Quickly was shown that this is possible. Can I also do it with the following syntax?

for(Node n : mySet) {
    mySet.remove(n);
}
+9  A: 

Yes, you can use the iterator to remove the current element safely:

iterator.remove();

The javadoc of remove() says:

Removes the specified element from this set if it is present (optional operation). More formally, removes an element e such that (o==null ? e==null : o.equals(e)), if this set contains such an element. Returns true if this set contained the element (or equivalently, if this set changed as a result of the call). (This set will not contain the element once the call returns.)


Answer to your next question: No, you can't. Modifying a set while iterating over it with an enhanced for loop will cause a ConcurrentModificationException.

tangens
And this is the only way you can modify the collection while iterating. Anything else will give you a ConcurrentModificationException.
Thilo
Thanks!!!!!!!!!
Peter Smit
A: 

The answer of tangens is correct. If you don't use iterator.remove() but remove directly from Set, you will receive an exception call ConcurrentModificationException

vodkhang
A: 

This ist what .remove() does:

http://download.oracle.com/javase/6/docs/api/java/util/Iterator.html#remove%28%29

"Removes from the underlying collection the last element returned by the iterator (optional operation). This method can be called only once per call to next. The behavior of an iterator is unspecified if the underlying collection is modified while the iteration is in progress in any way other than by calling this method. "

A: 

for(Node n : mySet) { mySet.remove(n); }

wont work since you are modifying the set you are iterating. This however can only be done using the iterator which is not the case this way.

This is one disadvantage of using enhanced for loops.

DerMike