Java.util.Map.put (key, value) - what if the value is equal to the existing value?

From the specification: "If the map previously contained a mapping for the key, the old value is replaced by the specified value." I'm interested in a situation where value.equals (old value), but value! = Old value. My reading of the specification is that the old value should still be replaced. Is it correct?

+4
source share
5 answers

If the new key matches the existing key, the displayed value will be replaced regardless of its value, for example. even if oldValue.equals(newValue) true .

I don’t think we need to look at the 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 with the specified value. (It is assumed that the mapping m contains the mapping for the key k if and only if m.containsKey (k) returns true.)

+4
source

There is no check for equality of values, only for key equality. The object will be replaced equal if the key you specified matches the key that is already on the map.

If the value was previously associated with the key, this value will be returned by the put method. Here is a snippet from the HashMap<K,V> source:

 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; } } 
+1
source

Yes, right. A simple test would tell 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)); 
+1
source

Yes, your understanding is correct if an equal value exists in map for the key , it will be replaced with the new value.

0
source

I think you're right. You can verify this with the code as follows:

 Map<String, String> strsMap = new HashMap<String, String>(); String myString1 = new String("mystring"); String myString2 = new String("mystring"); strsMap.put("str", myString1); System.out.println(myString1 == strsMap.put("str", myString2)); System.out.println(myString2 == strsMap.get("str"); 
0
source

Source: https://habr.com/ru/post/1436207/


All Articles