Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Set iterator, safe for removal of elements?

Tags:

java

iterator

set

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);
}
like image 706
Peter Smit Avatar asked Sep 28 '10 07:09

Peter Smit


2 Answers

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.

like image 76
tangens Avatar answered Nov 03 '22 00:11

tangens


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

like image 43
vodkhang Avatar answered Nov 02 '22 23:11

vodkhang