java - HashMap的key值不允许重复问题
高洛峰
高洛峰 2017-04-18 10:43:24
0
2
851
高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

reply all(2)
Peter_Zhu

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template