search

Home  >  Q&A  >  body text

java - HashMap的key值不允许重复问题

高洛峰高洛峰2885 days ago884

reply all(2)I'll reply

  • 天蓬老师

    天蓬老师2017-04-18 10:45:24

    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.

    reply
    0
  • PHP中文网

    PHP中文网2017-04-18 10:45:24

    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.

    reply
    0
  • Cancelreply