JAVA : HashMap -> Equals and HashCode
1. In HashMap (key, value) -> if we are adding string or int as key then no need of equals and hascode override, If we are using object (Eg : Employee) as a key then we need to override equals and hashcode method.
Below screen shot, since we are going to use Employee object as a key in HashMap, If we dont override hashCode method how HashMap behaves.
WithOut hashCode override:
With hashCode override:
Ref : https://www.youtube.com/watch?v=IwUwIrz9Ge8
Remember : (HashMap internally uses your hashCode to locate the index and your equals to verify the object is same) - shown in below image.
hasCode - is used to piston the emp object in the particular index of hashmap imlementation. (when you do get(e4) - 1st it checks in which index obj is there, so we must override hasCode() -
equals() - once it finds the index when we do get(e4) -> then it try to find the exact object located in that index using equals() method
What could happen if I only override equals
?
- Suppose you only override
equals
but nothashCode
- This means that
hashCode
is inherited fromObject
Object.hashCode
always tries to return different hash codes for different objects (regardless if they areequal
or not)- This means that you may end up with different hash codes for two objects that you consider to be
equal
- This in turn causes these two equal objects to end up in different buckets in hash based collections such as
HashSet
- This causes such collections to break
What could happen if I only override hashCode
?
This will not break the code as above, but may degrade performance.
- Suppose you only override
hashCode
but notequals
- This means that you may return the same hash code for two non-equal objects
Object.hashCode
might do so too, but it does an as good job as possible to avoid it
- This in turn means that two non-equal objects end up in the same bucket in a hash based collection such as
HashSet
- This degrades performance since objects are not distributed as evenly as possible among the buckets
- Put differently: If you don’t override
equals
any two objects will be considered non-equal. SinceObject.hashCode
ensures that all objects are distributed as evenly as possible in a hash based collectionObject.hashCode
is optimal, and overriding it with anything else will worsen the performance.

No comments:
Post a Comment