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

前端 未结 14 1328
余生分开走
余生分开走 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.

提交回复
热议问题