Reputation: 1445
I've read all the posts in the topic and I still have confusion on the following: when overriden and collision can happen? From what I'v read I see:
equals()
method, their hash code must be the sameequals()
method, we have no guarantee for theid hashcode()
, i.e. it might be the same, it might be differentHashMap.put(key, value)
HashMap compares objects by their equal()
method. If the two keys are equal()
then the new value
is overridenhashcode
then collision occurs and Java deals with ithashCode()
must be the same, so collision must happen, which is a contradiction with the previous?Can someone please clarify these steps for me?
Upvotes: 2
Views: 204
Reputation: 726479
Your point #3 comes too soon: HashMap compares for equality only when the hashCode
is the same.
HashMap
checks hash code first to determine the placement of the object in a bucket. The regular HashMap
keeps only items with identical hash codes (modulo a certain number) in the same bucket, and checks equality only for objects within the same bucket.
Upvotes: 2
Reputation: 234635
Think of a hashmap as a set of pigeon holes. Each pigeon hole can contain more than one object.
The hashCode()
return is used to select the pigeon hole which either contains or would contain that object.
The equals()
is used as the criterion to identify a specific object (e.g. for replacement).
The aim of hashCode()
is to disperse typical objects uniformly across the pigeon holes. Once a particular pigeon hole has been identified as possibly containing an object then all objects in that particular group have to be examined. That operation is expensive since equals()
needs to be called.
Upvotes: 4