java.util.Map.put(key, value) - what if value equals existing value?
Solution 1
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.)
Solution 2
Yes, it's right. A simple test would have told you:
Integer a = new Integer(1);
Integer b = new Integer(1);
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("key", a);
map.put("key", b);
System.out.println("Value is b : " + (map.get("key") == b));
Solution 3
There is no check for the value equality, only for the key equality. The object will be replaced by its equal if the key that you specified matches a key that is already in the map.
If a value has been associated with the key previously, that value will be returned by the put
method. Here is a snippet from the source of HashMap<K,V>
:
for (Entry<K,V> e = table[i]; e != null; e = e.next) {
Object k;
if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
V oldValue = e.value;
e.value = value;
e.recordAccess(this);
return oldValue;
}
}
philo
Software engineer on Google Play Store and Android Instant Apps teams.
Updated on May 12, 2020Comments
-
philo almost 4 years
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?