开发者

Java Set iterator, safe for removal of elements?

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 el开发者_Go百科ements 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


This has actually improved in Java 8. Now you can just

mySet.removeIf(element -> someConditionMatches());

The above is implemented as a default method in java.util.Collection and should save everyone from writing boring loops. That said, it should work for any type of collection, and not just Set.


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. "


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜