Friday, 13 October 2017

How does HashMap work internally in Java?


A HashMap in Java stores both key and value objects, in a bucket. It is stored as an Entry object that implements Map.Entry interface.
The key object used in a HashMap has to provide implementation for hashCode() and equals() methods.
When put() method is used to store a key-value pair, the HashMap implementation calls hashCode() method on Key object to calculate a hash that is used to find a bucket where Entry object will be stored.
When get() method is used to retrieve a value stored against a key object, we first calculate a hash of Key object. Then we use this hash to find the bucket in which that particular key is stored.
Once Key object’s location is found, it may happen that more than one Key is sored in same location. So now we use equals() method to find the exact Key object. Once the exact Key object is found we use it to get Value object.

No comments:

Post a Comment

Popular Posts