What happens if two different objects have the same hashcode?

后端 未结 5 1519
余生分开走
余生分开走 2020-12-28 17:23

It is my understanding that two unequal objects can have the same hashcode. How would this be handled when adding or retrieving from a HashMap java?

5条回答
  •  再見小時候
    2020-12-28 17:59

    In HashMap, keys along with their associative values are stored in a linked list node in the bucket and the keys are essentially compared in hashmap using equals() method not by hashcode.

    hm.put("a","aValue"); // Suppose hashcode created for key "a" is 209 
    hm.put("b","bValue"); // Here hashcode created for key "b" is 209 as well.
    
    • If a.equals(b) returns true, bValue will replace aValue and bValue will be returned.
    • If a.equals(b) returns false, another node will be created in the bucket list, so when you call get("b") you will get bValue since a.equals(b) is false.

提交回复
热议问题