How does a Java HashMap handle different objects with the same hash code?

前端 未结 14 1343
余生分开走
余生分开走 2020-11-22 02:27

As per my understanding I think:

  1. It is perfectly legal for two objects to have the same hashcode.
  2. If two objects are equal (using the equals() method)
14条回答
  •  难免孤独
    2020-11-22 03:21

    two objects are equal, implies that they have same hashcode, but not vice versa.

    2 equal objects ------> they have same hashcode

    2 objects have same hashcode ----xxxxx--> they are NOT equal

    Java 8 update in HashMap-

    you do this operation in your code -

    myHashmap.put("old","old-value");
    myHashMap.put("very-old","very-old-value");
    

    so, suppose your hashcode returned for both keys "old" and "very-old" is same. Then what will happen.

    myHashMap is a HashMap, and suppose that initially you didn't specify its capacity. So default capacity as per java is 16. So now as soon as you initialised hashmap using the new keyword, it created 16 buckets. now when you executed first statement-

    myHashmap.put("old","old-value");
    

    then hashcode for "old" is calculated, and because the hashcode could be very large integer too, so, java internally did this - (hash is hashcode here and >>> is right shift)

    hash XOR hash >>> 16
    

    so to give as a bigger picture, it will return some index, which would be between 0 to 15. Now your key value pair "old" and "old-value" would be converted to Entry object's key and value instance variable. and then this entry object will be stored in the bucket, or you can say that at a particular index, this entry object would be stored.

    FYI- Entry is a class in Map interface- Map.Entry, with these signature/definition

    class Entry{
              final Key k;
              value v;
              final int hash;
              Entry next;
    }
    

    now when you execute next statement -

    myHashmap.put("very-old","very-old-value");
    

    and "very-old" gives same hashcode as "old", so this new key value pair is again sent to the same index or the same bucket. But since this bucket is not empty, then the next variable of the Entry object is used to store this new key value pair.

    and this will be stored as linked list for every object which have the same hashcode, but a TRIEFY_THRESHOLD is specified with value 6. so after this reaches, linked list is converted to the balanced tree(red-black tree) with first element as the root.

提交回复
热议问题