philo
philo

Reputation: 3690

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?

Upvotes: 5

Views: 26043

Answers (5)

pb2q
pb2q

Reputation: 59617

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.)

Upvotes: 5

Brian
Brian

Reputation: 17309

I believe you are correct. You can check this with code like this:

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");

Upvotes: 0

JB Nizet
JB Nizet

Reputation: 691755

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));

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726589

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;
    }
}

Upvotes: 1

kosa
kosa

Reputation: 66637

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

Upvotes: 0

Related Questions