Java · OOP, JVM and backend craft
How does HashMap work internally?
Short answer
HashMap stores entries in a power-of-two bucket array. It spreads hashes, resolves collisions with linked lists that treeify under contention, and resizes when the load factor is exceeded.
A HashMap is an array of buckets. Each bucket holds a linked list of nodes, and since Java 8 a bucket can become a red-black tree. The default initial capacity is 16 and the default load factor is 0.75, so the table resizes when the number of entries exceeds 12.
The lookup path
- Compute the key hash and spread the high bits with hash XOR hash unsigned-shifted by 16
- Select the bucket with (capacity - 1) AND spreadHash
- Compare the hash, then the key by reference or equals
- On collision, walk the bin list or tree
static int bucketIndex(int hash, int capacity) {
int spread = hash ^ (hash >>> 16);
return (capacity - 1) & spread;
}When a bin grows past eight entries and the table has at least 64 buckets, the bin treeifies. Tree bins give O(log n) worst-case lookup within a collision chain instead of O(n). Resizing doubles capacity and redistributes entries. A bad hashCode that sends everything to one bucket degrades performance badly.
HashMap is not thread-safe. Concurrent writes can corrupt the table or lose entries. Use ConcurrentHashMap for shared access. Also keep keys immutable and consistent with equals, because a changed hash makes an entry unreachable.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1Why is the capacity a power of two?
- 2What is treeification and when does it happen?
- 3What happens when a HashMap resizes?
- 4Why can a poor hashCode destroy performance?
Say it in the interview
HashMap uses an array of buckets. It spreads the key hash, masks it with capacity minus one to pick a bucket, then compares hash and equals within that bucket. Collisions are handled by a linked list that becomes a red-black tree when the bin is large and the table is big enough. It resizes when the load factor is exceeded, is not thread-safe, and bad or mutable keys can make lookups degrade or disappear.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live Java mock interview and get scored feedback on depth, clarity and confidence.