philo philo - 6 months ago 15
Java Question

java.util.Map.put(key, value) - what if value equals existing value?

From the spec: "If the map previously contained a mapping for the key, the old value is replaced by the specified value." I'm wondering about the situation where value.equals(the old value) but value != the old value. My reading of the spec is that the old value must still be replaced. Is that right?

Answer

If a new key matches an existing key, the mapped value will be replaced regardless of it's value, e.g. even if oldValue.equals(newValue) is true.

I don't think that we need to look at source, or rely on test code: this is explicit from the documentation for Map.put, where we find:

If the map previously contained a mapping for the key, the old value is replaced by the specified value. (A map m is said to contain a mapping for a key k if and only if m.containsKey(k) would return true.)