简体   繁体   中英

Is it safe to delete HashMap's entry when iterating over its values?

Assuming I know the key, is it possible to remove it when iterating over

for (ExampleClass e : map.values()) {
    if (condition) {
        map.remove(key);
    }
}

I have found a related question ( iterating over and removing from a map ), but it assumes we are iterating over the key set. Does the same apply to the value set?

From the HashMap javadoc :

The iterators returned by all of this class's "collection view methods" are fail-fast: if the map is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove method, the iterator will throw a ConcurrentModificationException .

So you can't use map.remove(key) .

From the javadoc for HashMap#values() :

The collection supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Collection.remove, removeAll, retainAll and clear operations.

So you can use Iterator#remove() to remove entries from the value set.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM