How HashMap works Internally?
🔧 1. Storage Structure
HashMap
uses an array of buckets (Node[] table) where each bucket is a linked list or tree of Map.Entry
objects.
🔢 2. How a key-value pair is stored
When you put a value into a HashMap
:
Internally, it performs:
a. Hashing the key
The key’s hash code is calculated (using hashCode()
), and some bit manipulation is done to spread bits more evenly.
b. Index calculation
This index determines which bucket to use in the internal array.
c. Store the entry
- If the bucket is empty → store the entry.
- If not → check for key collision:
- If key exists → update value.
- If key is different → use chaining (linked list or tree) to store multiple entries.
⚠️ 3. Collision Handling
- Chaining is used — multiple entries in the same bucket using a linked list.
- From Java 8 onward, if the number of entries in a bucket > 8 and total buckets > 64, it becomes a Balanced Tree (Red-Black Tree) for faster lookups.
🔄 4. get(key)
Process
- Compute hash and bucket index.
- Go to the correct bucket.
- Traverse the linked list or tree to find the key.
- Return the value if key matches.
📏 5. Resizing
When size exceeds threshold = capacity × load factor
(default 0.75), the array is doubled, and all entries are rehashed to new buckets.
🧠 Summary Diagram (Text)
🔍 Performance
-
put()
andget()
→ O(1) average case. - In worst case (many collisions) → O(n), but tree optimization improves it to O(log n).
HashMap
With a key having multiple values
✅ Example using HashMap<String, List<String>>
:
🧾 Output:
🔍 Explanation:
-
computeIfAbsent()
checks if the key exists; if not, it initializes an empty list. - Then you can add multiple values to the same key.