Skip to main content

๐Ÿงญ My Deep Dive Into HashMap Internals ๐Ÿ”‘๐Ÿช„

 

๐Ÿ‘‹ Everyone knows HashMap as “key & value”… but what’s inside?

Honestly, I was also in that majority who just knew:


๐Ÿ‘‰ “HashMap = key & value storage.”
…and never cared how it actually works under the hood.


But recently I got curious and explored it myself, and here’s what I learned ๐Ÿ‘‡ (sharing in case it helps someone else too ๐Ÿ’›).


๐Ÿ”ง HashMap, HashSet, HashTable — what do they use internally?

All of them rely on a common concept: Hashing Technique


…but there’s more happening than I expected!



๐Ÿ—️ How does Hashing work here?

Think of it as splitting data into an array of buckets:


✅ Each bucket holds entries (key → value).

✅ When you insert, the hash function decides which bucket to drop your data into.

➡️ In Java:

  • Your key’s hashCode() is used.

  • That hash code is transformed into a bucket index.

  • Inside that bucket, Java stores a Map.Entry (key and value pair).


Why override hashCode()?
✔️ To give a good distribution → fewer collisions → faster lookups.


Why override equals() too?

✔️ To correctly compare keys inside the same bucket.


๐Ÿ’ก What algorithm?

I initially guessed B+ Tree (๐Ÿค”) — but that’s not what HashMap uses.


Here’s what I found out:
HashMap uses a combination of Hash Table + Linked List / Red‑Black Tree (from Java 8 onwards):

  • Normally, each bucket stores entries in a linked list.

  • If too many collisions occur in one bucket (default threshold = 8 entries), that bucket switches to a balanced Red‑Black Tree for faster lookups.


๐Ÿ˜ฏ My sudden doubt…

While digging deeper into HashMap internals, I came across this line:

“If too many collisions occur in one bucket (default threshold = 8 entries), that bucket switches to a balanced Red‑Black Tree for faster lookups.”

๐Ÿ‘‰ Wait… what does that really mean? ๐Ÿคจ
At first, I only knew HashMap stores entries in buckets using hashing.

But this line made me pause and explore further. ๐Ÿ”


๐Ÿงญ My exploration & what I found

When two different keys produce the same bucket index (because their hashCode() after processing points to the same slot), they collide and get stored together.

Before digging in, my assumption:

“Hmm, maybe HashMap just keeps chaining them in a list…?”

Then I found out:
✅ Yes! In older Java (before 8), each bucket was a Linked List.
✅ But if many entries land in the same bucket, searching becomes slow because it goes one by one.

๐Ÿ‘‰ O(n) time in worst cases. ๐Ÿ˜ฉ


๐ŸŒณ The optimization I discovered

In Java 8 and above, the designers made it smarter:


✅ If a single bucket gets too many entries (more than 8),
✅ HashMap converts that bucket’s linked list into a Red‑Black Tree ๐ŸŒณ.

Why is that cool?
Because searching in a balanced tree is logarithmic (O(log n)),
instead of linear (O(n)).

➡️ Even with many collisions, lookups remain fast! ⚡


How it feels now

It’s like I opened a hidden drawer inside HashMap:


ConditionStructure  Search Time
     Few collisions (≤8)       Linked List         O(n) for that bucket
Too many collisions (>8)   ๐ŸŒณ Red‑Black Tree      O(log n) for that bucket

๐Ÿ’ก Mind blown moment:

“Wow! HashMap dynamically upgrades its internal structure for performance!” ๐Ÿคฏ


So nope, not B+ Tree — it’s Red‑Black Tree in modern Java HashMap.


(TreeMap itself is always a Red‑Black Tree, not hashing.)


๐ŸŒณ What about others?

HashSet → Internally just a HashMap with dummy values.
HashTable → Older synchronized version of HashMap (still hashing).
LinkedHashMap → Keeps insertion order with a linked list alongside hashing.
TreeMap → Completely different, uses a Red‑Black Tree (no hashing).
ConcurrentHashMap → Advanced locking & segmenting, but still hashing.




๐Ÿ”ฅ Key Takeaways (My own “aha!” moments):

✅ HashMap isn’t just a simple bucket → it’s smart with hash functions and trees.
✅ Overriding hashCode() and equals() properly is super important.
✅ Different map/set implementations use different internal structures—choose wisely!




Comments

Popular posts from this blog

๐Ÿ” Is final Really Final in Java? The Truth May Surprise You ๐Ÿ˜ฒ

๐Ÿ’ฌ “When I was exploring what to do and what not to do in Java, one small keyword caught my eye — final . I thought it meant: locked, sealed, frozen — like my fridge when I forget to defrost it.”   But guess what? Java has its own meaning of final… and it’s not always what you expect! ๐Ÿ˜… Let’s break it down together — with code, questions, confusion, jokes, and everything in between. ๐ŸŽฏ The Confusing Case: You Said It's Final... Then It Changed?! ๐Ÿซ  final List<String> names = new ArrayList <>(); names.add( "Anand" ); names.add( "Rahul" ); System.out.println(names); // [Anand, Rahul] ๐Ÿคฏ Hold on... that’s final , right?! So how on earth is it still changing ? Time to dive deeper... ๐Ÿง  Why Is It Designed Like This? Here’s the key secret: In Java, final applies to the reference , not the object it points to . Let’s decode this like a spy mission ๐Ÿ•ต️‍♂️: Imagine This: final List<String> names = new ArrayList <>(); Be...

๐ŸŽข Java Loops: Fun, Fear, and ForEach() Fails

๐ŸŒ€ Oops, I Looped It Again! — The Ultimate Java Loop Guide You Won't Forget “I remember this question from one of my early interviews — I was just 2 years into Java and the interviewer asked, ‘Which loop do you prefer and why?’” At first, I thought, “Duh! for-each is cleaner.” But then he grilled me with cases where it fails. ๐Ÿ˜ต That led me to explore all loop types, their powers, and their pitfalls. Let’s deep-dive into every major Java loop with examples &  real-world guidance so you'll never forget again. ๐Ÿ” Loop Type #1: Classic For Loop — “The Old Reliable” ✅ When to Use: You need an index You want to iterate in reverse You want full control over loop mechanics ✅ Good Example: List<String> names = List.of("A", "B", "C"); for (int i = 0; i < names.size(); i++) { System.out.println(i + ": " + names.get(i)); } ๐Ÿ”ฅ Reverse + Removal Example: List<String> item...

๐Ÿงต Virtual Threads in Java — The Ultimate Guide with Diagrams, Code & Interview Qs!

๐Ÿš€ “How are Virtual Threads different from Thread Pools?” ๐Ÿ˜ต “Are they OS threads or JVM threads?” ๐Ÿ™ƒ “Should I still use CompletableFuture?” ๐Ÿคฏ “How do I even use them in real-time microservices?” ๐Ÿง  What are Virtual Threads? Virtual Threads (introduced in Java 21 as stable ๐ŸŽ‰) are lightweight threads managed by the JVM instead of the OS kernel. ๐Ÿ‘‰ They look like normal threads, but don’t hog OS resources like traditional threads. ๐Ÿง  What is the OS Kernel? ๐Ÿ›️ OS Kernel = The Brain of the Operating System It’s the core part of your OS (Windows, Linux, Mac) that: Manages memory ๐Ÿง  Schedules threads ๐Ÿ•’ Talks to hardware ๐Ÿ’ป Handles I/O operations ๐Ÿ“จ When you create a traditional thread in Java, the JVM asks the OS Kernel to create a real OS-level thread. ๐Ÿ–ผ️ Imagine This... ┌───────────────────────────┐ │ Your Java Application │ └────────────┬──────────────┘ │ ...