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

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

    I will not get into the details of how HashMap works, but will give an example so we can remember how HashMap works by relating it to reality.

    We have Key, Value ,HashCode and bucket.

    For sometime, we will relate each of them with the following:

    • Bucket -> A Society
    • HashCode -> Society's address(unique always)
    • Value -> A House in the Society
    • Key -> House address.

    Using Map.get(key) :

    Stevie wants to get to his friend's(Josse) house who lives in a villa in a VIP society, let it be JavaLovers Society. Josse's address is his SSN(which is different for everyone). There's an index maintained in which we find out the Society's name based on SSN. This index can be considered to be an algorithm to find out the HashCode.

    • SSN Society's Name
    • 92313(Josse's) -- JavaLovers
    • 13214 -- AngularJSLovers
    • 98080 -- JavaLovers
    • 53808 -- BiologyLovers

    1. This SSN(key) first gives us a HashCode(from the index table) which is nothing but Society's name.
    2. Now, mulitple houses can be in the same society, so the HashCode can be common.
    3. Suppose, the Society is common for two houses, how are we going to identify which house we are going to, yes, by using the (SSN)key which is nothing but the House address

    Using Map.put(key,Value)

    This finds a suitable society for this Value by finding the HashCode and then the value is stored.

    I hope this helps and this is open for modifications.

    0 讨论(0)
  • 2020-11-22 03:33

    You're mistaken on point three. Two entries can have the same hash code but not be equal. Take a look at the implementation of HashMap.get from the OpenJdk. You can see that it checks that the hashes are equal and the keys are equal. Were point three true, then it would be unnecessary to check that the keys are equal. The hash code is compared before the key because the former is a more efficient comparison.

    If you're interested in learning a little more about this, take a look at the Wikipedia article on Open Addressing collision resolution, which I believe is the mechanism that the OpenJdk implementation uses. That mechanism is subtly different than the "bucket" approach one of the other answers mentions.

    0 讨论(0)
提交回复
热议问题