Sandy
Sandy

Reputation: 14135

Collision resolution in HashMap

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().

Upvotes: 5

Views: 3944

Answers (2)

Patricia Shanahan
Patricia Shanahan

Reputation: 26185

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().

Upvotes: 3

Andrew Logvinov
Andrew Logvinov

Reputation: 21851

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().

Upvotes: 9

Related Questions