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

前端 未结 14 1350
余生分开走
余生分开走 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:26

    Hash map works on the principle of hashing

    HashMap get(Key k) method calls hashCode method on the key object and applies returned hashValue to its own static hash function to find a bucket location(backing array) where keys and values are stored in form of a nested class called Entry (Map.Entry) . So you have concluded that from the previous line that Both key and value is stored in the bucket as a form of Entry object . So thinking that Only value is stored in the bucket is not correct and will not give a good impression on the interviewer .

    • Whenever we call get( Key k ) method on the HashMap object . First it checks that whether key is null or not . Note that there can only be one null key in HashMap .

    If key is null , then Null keys always map to hash 0, thus index 0.

    If key is not null then , it will call hashfunction on the key object , see line 4 in above method i.e. key.hashCode() ,so after key.hashCode() returns hashValue , line 4 looks like

                int hash = hash(hashValue)
    

    and now ,it applies returned hashValue into its own hashing function .

    We might wonder why we are calculating the hashvalue again using hash(hashValue). Answer is It defends against poor quality hash functions.

    Now final hashvalue is used to find the bucket location at which the Entry object is stored . Entry object stores in the bucket like this (hash,key,value,bucketindex)

提交回复
热议问题