简体   繁体   中英

Concurrent Modification exception when only values of Hashmap are modified

I have code like below, in which the inner loop modifies the Hashmap, but only in a way that no new keys are added or deleted, but only the values are updated. Does this qualifies as modification of a Hashmap, for Concurrent Modification Exception to be thrown ? In current tests that I have done, I haven't found any exception to be thrown though.

for(String variable:variableMap.descendingKeySet()) {
        for (String innerVariable : variableMap.keySet()) {
            variableMap.put(innerVariable, variableMap.get(innerVariable).replace("$" + variable, variableMap.get(variable)));
        }
    }

See the Javadoc of HashMap :

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 .

Now what is "structurally modified" ?

A structural modification is any operation that adds or deletes one or more mappings; merely changing the value associated with a key that an instance already contains is not a structural modification.

So, no, you won't get a ConcurrentModificationException if you only modify the value of the key.

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