仅修改 Hashmap 的值时的并发修改异常

Concurrent Modification exception when only values of Hashmap are modified

我有如下代码,其中内部循环修改哈希图,但只是以不添加或删除新键的方式进行,而只更新值。这是否符合 Hashmap 的修改,以抛出并发修改异常?在我目前所做的测试中,我还没有发现任何异常被抛出。

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

查看 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.

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

所以,不,如果您只修改键的值,您将不会得到 ConcurrentModificationException