Hashcode collision
HashMap uses hash code (it's a numeric value) of key object to locate the entry.
Hashcode value of key object decide index of array where value object get stored.
Hashcode – equals rule
1. Objects that are equal according to the equals method must return the same hashCode value.
2. If two objects are not equal according to equals, they are not required to return different hashCode values.
So according to this rule, It is possible that two different object may have same hashcode values, this is called hashcode collision.
To overcome this problem, concept of bucket has been introduced. All the Value objects whose corresponding Key’s hashcode values are same, they fall under same bucket.
Hashcode collision example
There are three key-value entries are shown , out of which second and third has same hashcode , that 's why they kept under same bucket. |
Both objects will be stored in same bucket but second object will be stored in next node of linked list.
Then, key' s equals () method will be used to identify correct key / value pair in HashMap.
No comments:
Post a Comment
Note: only a member of this blog may post a comment.