1

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)));
        }
    }
1
  • 1
    Note that you can replace the inner loop with variableMap.replaceAll((k, v) -> v.replace("$" + variable, variableMap.get(variable))). Commented May 21, 2018 at 4:39

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

To add one point: You can also use entrySet's setValue to set value for a key (Similar to setting a value for an existing key as in the OP and hence the same behavior)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.