What happens to the lookup in a Hashmap or Hashset when the objects Hashcode changes

后端 未结 4 452
太阳男子
太阳男子 2021-01-04 10:00

In a Hashmap the hash code of the key provided is used to place the value in the hashtable. In a Hashset the obects hashcode is used to place the value in the underlying has

4条回答
  •  迷失自我
    2021-01-04 10:54

    The HashSet is backed up by a HashMap.

    From the javadocs.

    This class implements the Set interface, backed by a hash table (actually a HashMap instance).

    So if you change the hashcode, I doubt whether you can access the object.

    Internal Implementation Details

    The add implementation of HashSet is

     public boolean add(E e) {
            return map.put(e, PRESENT)==null;
     }
    

    The key is the elem and value is just a dummy Object called PRESENT

    and the contains implementation is

    public boolean contains(Object o) {
            return map.containsKey(o);
    }
    

提交回复
热议问题