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);
}
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
.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With