I recommend you take a look at the principle of Map When map stores values, it does not use the address of the object, but the hashcode of the object. You first put p1 as the key into the map, and then change the value of p1. At this time The hashcode of p1 has changed. When it was stored again, map thought it was a different key, so it saved it.
The following is the internal implementation of HashMap.put
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
After p1.setAge(5), the hashCode of p1 changes, and the hash(key) in the above function changes. Although the key is the same object, HashMap still stores it as a new key.
For efficiency reasons, this scenario is not supported. It can be regarded as a pitfall of HashMap.
I recommend you take a look at the principle of Map
When map stores values, it does not use the address of the object, but the hashcode of the object.
You first put p1 as the key into the map,
and then change the value of p1. At this time The hashcode of p1 has changed. When it was stored again, map thought it was a different key, so it saved it.
The following is the internal implementation of HashMap.put
After p1.setAge(5), the hashCode of p1 changes, and the hash(key) in the above function changes. Although the key is the same object, HashMap still stores it as a new key.
For efficiency reasons, this scenario is not supported. It can be regarded as a pitfall of HashMap.