HashMap is the most used collection in Java after ArrayList, and “how does HashMap work internally?” is a favourite interview question. You do not need to memorise the source code, but you should be able to explain the main idea clearly.
The basic idea: buckets
A HashMap keeps an internal array of buckets. When you call put(key, value):
- Java calls
key.hashCode()to get an integer. - That number is turned into a bucket index.
- The key-value pair is stored in that bucket.
When you call get(key), Java computes the same index, goes straight to that bucket and uses equals() to find the exact key. That is why lookups are usually very fast, close to constant time.
Collisions
Two different keys can land in the same bucket. This is a collision, and it is normal. The bucket then holds several entries, and equals() decides which one matches. Since Java 8, a bucket with many entries is converted from a linked list into a balanced tree, so even bad cases stay reasonably fast.
Why hashCode and equals must agree
If you use your own class as a key, you must override both hashCode() and equals(), and two objects that are equal must return the same hash code. If you override only equals(), two “equal” keys may go to different buckets, and get() will return null for a key you just inserted. IDEs and Java records generate correct versions for you.
Resizing
When the map gets about 75% full (the default load factor of 0.75), it doubles its bucket array and redistributes entries. If you know you will store many items, pass an initial capacity to avoid repeated resizing.
Quick interview facts
- HashMap allows one null key and many null values.
- It is not thread-safe; use
ConcurrentHashMapwhen several threads write. - It does not keep insertion order; use
LinkedHashMapif order matters, orTreeMapfor sorted keys. - Keys should be immutable, such as String or Integer, so their hash code never changes.
Related: Java collections: List, Set and Map and Java multithreading basics.
These topics are practised with projects and mock interviews in our Java Full Stack course in Bangalore.
Book a free demo class at our BTM Layout centre, and ask a counsellor for batch details.
