How HashMap work in Java


If someone had asked me a year ago how HashMap works, I would've confidently said,


"It's just a key-value pair that uses hashing to store data."

Technically, I wasn't wrong.

But I wasn't completely right either.

While preparing for interviews, I decided to go beyond the definition.

That's when I discovered what actually happens inside a HashMap.

It isn't just a collection of random buckets.

At its core, HashMap uses a dynamic array.

Each position in that array is called a bucket.

When you insert a key, Java calculates its hashCode() to decide which bucket it belongs to.

But what if two different keys end up in the same bucket?

That's called a collision.

Instead of overwriting the existing value, HashMap stores both entries together.

Java then uses equals() to identify the correct key when retrieving data.

Earlier versions stored collided entries as a Linked List.

But in Java 8 and above, if too many entries accumulate in the same bucket (and the table is large enough), the linked list is converted into a Red-Black Tree.

That small optimization improves lookup performance from O(n) to O(log n) in worst-case scenarios.



View image

Comments

Popular posts from this blog

Async/await

Valid Parentheses

First negative in every window of size k