5

When we put key-value pair in HashMap this could happen the hashcode of two keys could be same then how in this condition storing and retrieval of key-value will be handled.

Update

What I understand so far is that if two object key has same hash code then both key objects will be stored in same bucket and when I will say get(key) then out of two objects with matching hashcode which element to fetch is decided by object.equals().

2

2 Answers 2

9

When you want to retrieve some object from hashmap and there exists several objects with the same hashcode, java will call equals() to determine the right object.

That is why it is so important to override equals() when overriding hashCode().

Sign up to request clarification or add additional context in comments.

2 Comments

thanks for simple and clear answer but I still have confusion so can you please comment on update of my question
Yes, that's right. We will iterate over the list of keys in the bucket and call equals() on our key comparing it with each of them until we find a match.
3

Each bucket is represented by a linked list, so there is no limit, other than heap space, on the number of entries in a bucket. There are fewer buckets than possible hashCode results, so multiple hash codes are mapped to the same bucket, not just keys with the same hashCode.

A hashCode() with many collisions, or a HashMap with too few buckets, can make some linked lists long. Good performance depends on short linked lists, because the final stage in a look up is a linear scan of one of the linked lists.

I agree with the previous answer that a match depends on both equals() and hashCode().

1 Comment

+1 for "There are fewer buckets than possible hashCode results, so multiple hash codes are mapped to the same bucket, not just keys with the same hashCode"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.