How HashMap Works in Java ?

In Java, a HashMap works on the concept of hashing.

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 stored 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.



You May Interest

What is a Singleton Class in Java ?

How Can We Reference an Unreferenced Object Again in Java ?

How Can You Determine If Your Program Has a Deadlock in Java ?

When Will You Use Strategy Design Pattern in Java ?

What is the Use of a Dictionary Class in Java ?