HashMap Internals
HashMap internals: hashing, buckets, load factor, resizing, collision handling and treeification
- Trace how HashMap stores and retrieves a key-value pair step by step
- Understand load factor, capacity, and rehashing thresholds
- Explain treeification (linked list → red-black tree at threshold 8)
Table of Contents
- Why Map is Not a Child of Collection
- Map Interface — Overview
- Map.Entry — The Sub-Interface
- HashMap — Data Structure Internals
- The Node (Entry) Structure
- How
put()Works — Step by Step - Collision and Chaining
- How
get()Works — Step by Step - The
hashCode()andequals()Contract - Load Factor and Rehashing
- Treeify Threshold — Linked List to BST
- Time Complexity of HashMap
- HashMap Methods — Full Reference with Examples
- HashMap vs HashTable vs ConcurrentHashMap
- Common Mistakes
- Best Practices
- Interview Notes
- Practice Questions
- Summary Revision Bullets
1. Why Map is Not a Child of Collection
The Core Reason
Every structure under the Collection interface — List, Set, Queue, Stack — deals with a sequence of single values:
1Collection holds: [ value1, value2, value3, value4 ]All methods in Collection (add(e), remove(e), contains(e), size(), etc.) are designed to operate on individual values.
Map, however, deals with key-value pairs:
1Map holds: { key1=value1, key2=value2, key3=value3 }This is fundamentally different — every operation now involves two things (a key and a value), not one. Methods like get(key), put(key, value), containsKey(key), containsValue(value) don't fit the Collection API at all.
Map is a completely separate interface hierarchy from Collection. It does not extend Collection or Iterable. This is by design — forcing Map to extend Collection would require shoehorning key-value semantics into single-value methods, which would be misleading and broken.The Java Collection Hierarchy Big Picture
HashSet internally uses HashMap. LinkedHashSet internally uses LinkedHashMap. TreeSet internally uses TreeMap. This is why understanding Map first is essential before studying Set.2. Map Interface Overview
Definition
AMapis an object that maps keys to values. It cannot contain duplicate keys. Each key maps to at most one value. Values can be duplicated.
Key Properties
| Property | Detail |
|---|---|
| Duplicate keys | ❌ Not allowed |
| Duplicate values | ✅ Allowed |
| Null keys | Depends on implementation (HashMap: yes, HashTable: no) |
| Null values | Depends on implementation (HashMap: yes, HashTable: no) |
| Order maintained | Depends (HashMap: no, LinkedHashMap: yes, TreeMap: sorted) |
Map Implementations
| Implementation | Ordering | Thread-Safe | Null Keys/Values |
|---|---|---|---|
HashMap | None | ❌ No | ✅ Both allowed |
LinkedHashMap | Insertion order | ❌ No | ✅ Both allowed |
TreeMap | Sorted (natural/comparator) | ❌ No | ❌ No null keys |
HashTable | None | ✅ Yes | ❌ Neither allowed |
ConcurrentHashMap | None | ✅ Yes | ❌ No nulls |
Commonly Used Map Methods
| Method | Description |
|---|---|
size() | Returns number of key-value mappings |
isEmpty() | Returns true if map has no entries |
containsKey(key) | Returns true if the key exists |
containsValue(value) | Returns true if the value exists |
get(key) | Returns value for key, or null if absent |
put(key, value) | Inserts or overwrites key-value pair |
putIfAbsent(key, value) | Inserts only if key absent or value is null |
remove(key) | Removes key-value pair, returns removed value |
getOrDefault(key, default) | Returns value or default if key absent |
keySet() | Returns a Set of all keys |
values() | Returns a Collection of all values |
entrySet() | Returns a Set of all pairs |
3. Map.Entry The Sub-Interface
What is `Map.Entry`?
Inside the Map interface, there is a nested sub-interface called Entry. This represents a single key-value pair (one row in the map).
1// Conceptually inside java.util.Map:2public interface Map<K, V> {3 interface Entry<K, V> {4 K getKey();5 V getValue();6 V setValue(V value);7 }8 // ... other methods9}Why Does It Exist?
When you iterate over a Map, you need an object that carries both the key and value together. Map.Entry is exactly that object — it bundles a key and a value into a single unit that can be returned, stored, or passed around.
How It Is Used
1Map<Integer, String> map = new HashMap<>();2map.put(1, "Alice");3map.put(2, "Bob");4
5// entrySet() returns Set<Map.Entry<Integer, String>>6for (Map.Entry<Integer, String> entry : map.entrySet()) {7 System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());8}4. HashMap Data Structure Internals
High-Level Structure
Internally, HashMap stores data in an array of linked list nodes (called a hash table). Each slot in the array is called a bucket or bin.
1HashMap internal structure (default size 16):2
3Index: [0] [1] [2] [3] [4] ... [15]4 | | |5 Node Node Node6 |7 Node ← collision chain (linked list)8 |9 NodeEach Node in the array (and in the chain) holds four things:
hash— the computed hash of the keykey— the key of the mappingvalue— the value of the mappingnext— a reference to the next Node (for collision chaining)
Default Configuration
| Configuration | Default Value |
|---|---|
| Initial array capacity | 16 |
| Load factor | 0.75 |
| Treeify threshold (linked list → tree) | 8 |
| Untreeify threshold (tree → linked list) | 6 |
1// Creating a HashMap with all defaults:2Map<Integer, String> map = new HashMap<>();3// Internal array size = 16, load factor = 0.754
5// Creating with custom initial capacity:6Map<Integer, String> map = new HashMap<>(32);7
8// Creating with custom capacity and load factor:9Map<Integer, String> map = new HashMap<>(32, 0.5f);5. The Node (Entry) Structure
Node Definition (inside HashMap)
1// Simplified from OpenJDK source:2static class Node<K, V> implements Map.Entry<K, V> {3 final int hash; // cached hash of the key4 final K key; // the key5 V value; // the value6 Node<K, V> next; // pointer to next node (for chaining)7
8 Node(int hash, K key, V value, Node<K, V> next) {9 this.hash = hash;10 this.key = key;11 this.value = value;12 this.next = next;13 }14
15 public K getKey() { return key; }16 public V getValue() { return value; }17 // ...18}Memory Representation
1HashMap object2│3└── Node[] table (array of size 16 by default)4 │5 ├── [0] → null6 ├── [1] → Node { hash=1234567, key=1, value="SJ", next=null }7 ├── [2] → Node { hash=984120, key=5, value="PJ", next=null }8 │ ↓9 │ Node { hash=515100, key=10, value="KJ", next=null }10 ├── [3] → null11 ...12 └── [15] → null6. How `put()` Works Step by Step
The Algorithm
When you call map.put(key, value), HashMap performs these steps:
Concrete Example Inserting into a Size-3 HashMap
Let's use a simplified size-3 array: indices [0], [1], [2].
Insert `put(1, "SJ")`
- Compute hash of key
1→ e.g.,1234567 - Index =
1234567 mod 3=1 table[1]is empty → insert Node{hash=1234567, key=1, value="SJ", next=null}
1[0] → null2[1] → { hash=1234567, key=1, value="SJ", next=null }3[2] → nullInsert `put(5, "PJ")`
- Compute hash of key
5→ e.g.,984120 - Index =
984120 mod 3=2 table[2]is empty → insert Node{hash=984120, key=5, value="PJ", next=null}
1[0] → null2[1] → { key=1, value="SJ", next=null }3[2] → { key=5, value="PJ", next=null }Insert `put(10, "KJ")` **Collision!**
- Compute hash of key
10→ e.g.,515100 - Index =
515100 mod 3=1 table[1]is NOT empty → collision!- Check: is existing key (
1) == new key (10)? → No - Traverse chain; end of chain reached (next is null)
- Append new node:
{hash=515100, key=10, value="KJ", next=null}
1[0] → null2[1] → { key=1, value="SJ", next=→ }3 ↓4 { key=10, value="KJ", next=null }5[2] → { key=5, value="PJ", next=null }Insert `put(1, "MJ")` **Duplicate Key (Overwrite)**
- Compute hash of key
1→1234567 - Index =
1 table[1]is not empty → check: existing key (1) == new key (1)? → Yes- Overwrite:
value = "MJ"
1[1] → { key=1, value="MJ", next=→ } ← value updated2 ↓3 { key=10, value="KJ", next=null }7. Collision and Chaining
What is a Collision?
A collision occurs when two different keys produce the same array index after hashing and mod operations. This is expected and unavoidable in any hash table.
1hash("cat") mod 16 = 52hash("dog") mod 16 = 5 ← collision! Both map to index 5How HashMap Resolves Collisions Separate Chaining
HashMap uses separate chaining: when a collision occurs, the new node is linked to the existing node at that index, forming a linked list (chain).
1Before collision:2[5] → { key="cat", value=1, next=null }3
4After collision (adding "dog"):5[5] → { key="cat", value=1, next=→ }6 ↓7 { key="dog", value=2, next=null }This chain can grow indefinitely — but HashMap has mechanisms (load factor, treeify threshold) to prevent it from becoming too long.
8. How `get()` Works Step by Step
The Algorithm
Concrete Example `get(5)`
Using our earlier map state:
1[0] → null2[1] → { key=1, value="SJ", next=→ } → { key=10, value="KJ", next=null }3[2] → { key=5, value="PJ", next=null }- Compute hash of
5→984120(same hash function, same result — guaranteed) - Index =
984120 mod 3=2 - Go to
table[2] - Node at
table[2]: checkhash == 984120✓ ANDkey.equals(5)✓ → match! - Return
"PJ"
Concrete Example `get(10)` (requires chain traversal)
- Compute hash of
10→515100 - Index =
515100 mod 3=1 - Go to
table[1] - Node:
key=1→hash match? Yes (515100 == ... wait — 1's hash was 1234567)→ No match
key.equals(nodeKey) is true, it's a match. This two-step check is why the hashCode/equals contract is critical.- Move to
next→ Node:key=10, check hash + equals → match! - Return
"KJ"
9. The `hashCode()` and `equals()` Contract
Why This Contract Exists
The get() and put() operations rely on two things:
hashCode()to find the right bucket (array index)equals()to find the right node within that bucket
These two methods must work together consistently. Java defines a formal contract between them.
The Two Rules of the Contract
Rule 1 Same objects MUST have the same hash
Ifobject1.equals(object2)istrue, thenobject1.hashCode() == object2.hashCode()MUST also betrue.
Why this matters for HashMap:
When you call put(key, value), HashMap computes hashCode(key) and stores the node at a certain index.
Later, when you call get(key), HashMap must compute hashCode(key) again and arrive at the same index. If equals says they're the same object but hashCode gives different results, get will look in the wrong bucket and return null — even though the key exists!
1// Correct: same object → same hash every time2// hashCode(5) called at put time → 6161003// hashCode(5) called at get time → 616100 ✓ (same bucket found)Rule 2 Same hash does NOT mean same objects
Ifobject1.hashCode() == object2.hashCode(), it does NOT meanobject1.equals(object2).
Why this is true:
A hash function maps an infinite space of possible values into a finite number of buckets. Collisions are inevitable — two completely different objects can have the same hash. This is normal and expected.
1hash(6) → 515102hash(8) → 51510 ← same hash, but 6 ≠ 8This is why HashMap stores both the hash AND the key, and checks both during lookup. Two nodes with the same hash at the same bucket are not necessarily the same entry.
Contract Summary Table
| Scenario | equals() result | hashCode() requirement |
|---|---|---|
obj1 and obj2 are logically equal | true | MUST be equal |
obj1 and obj2 are NOT equal | false | May or may not be equal (collision is OK) |
| Same hash | N/A | Does NOT imply equality |
equals() in a class, you MUST also override hashCode() consistently. Failing to do so breaks HashMap behavior: objects that are logically equal may end up in different buckets and get() will fail to find them.Practical Example
1class Point {2 int x, y;3
4 Point(int x, int y) { this.x = x; this.y = y; }5
6 // If we override equals but NOT hashCode — HashMap breaks!7 @Override8 public boolean equals(Object o) {9 Point p = (Point) o;10 return this.x == p.x && this.y == p.y;11 }12
13 // MUST also override hashCode:14 @Override15 public int hashCode() {16 return 31 * x + y; // consistent with equals17 }18}19
20Map<Point, String> map = new HashMap<>();21map.put(new Point(1, 2), "origin");22System.out.println(map.get(new Point(1, 2))); // "origin" — works correctly10. Load Factor and Rehashing
The Problem Load Factor Solves
Imagine a HashMap with only 3 buckets and 100 entries. All 100 would inevitably chain together in a few buckets, creating long linked lists. Every get() call would need to traverse most of the list — performance degrades to O(N).
Load factor prevents this by triggering an expansion of the array before it gets too crowded.
Definition
Load Factor
is a threshold that controls when the HashMap's internal array is resized (rehashed). It is a float value between 0 and 1.
1Threshold = Initial Capacity × Load Factor2 = 16 × 0.753 = 12When the number of key-value mappings reaches this threshold (12 in the default case), HashMap doubles the array size and rehashes all existing entries.
Rehashing Process
When the threshold is crossed:
- A new array of double the size is allocated (16 → 32 → 64 → 128…, always powers of 2).
- Every existing node is re-hashed:
hash mod newSizeis computed for each entry. - Entries are redistributed into the new, larger array.
- Previously colliding entries may now land in different buckets, reducing chain length.
Why Always Double (Powers of 2)?
Using powers of 2 for the array size allows the index calculation to use a bitwise AND instead of modulo:
1index = hash & (capacity - 1) // bitwise AND — very fast2// equivalent to:3index = hash % capacity // modulo — slowerThis is a performance optimization in the JDK implementation.
Choosing Load Factor
| Load Factor | Effect |
|---|---|
| Low (e.g. 0.25) | Rehash earlier → more memory used, fewer collisions, faster lookups |
| High (e.g. 0.9) | Rehash later → less memory used, more collisions, slower lookups |
| Default (0.75) | Balanced trade-off between time and space |
0.75 is optimal. Only tune it if you have specific performance profiling data.11. Treeify Threshold Linked List to BST
The Problem
Even with load factor and rehashing, there is still a worst-case scenario: a poorly written or malicious hashCode() implementation that returns the same hash for many different keys. This causes all entries to pile into one bucket as a long linked list.
In a linked list of N nodes, every search requires O(N) time in the worst case.
The Solution Treeify Threshold
HashMap has a second line of defense: if a single bucket's chain length reaches 8 nodes, the linked list is converted into a Red-Black Tree (a self-balancing binary search tree).
1BEFORE treeify (linked list — O(N) search):2
3[3] → Node1 → Node2 → Node3 → Node4 → Node5 → Node6 → Node7 → Node84
5 ↓ (9th insertion triggers treeify)6
7AFTER treeify (Red-Black Tree — O(log N) search):8
9[3] → Node410 / \11 Node2 Node612 / \ / \13 Node1 Node3 Node5 Node714 \15 Node8Why Red-Black Tree?
A simple Binary Search Tree (BST) can degenerate into a linked list if keys are inserted in sorted order (making it O(N) again). A Red-Black Tree is a self-balancing BST that guarantees O(log N) height at all times, making search, insert, and delete all O(log N).
Treeify and Untreeify Thresholds
| Threshold | Value | Meaning |
|---|---|---|
TREEIFY_THRESHOLD | 8 | Chain of length ≥ 8 → convert to Red-Black Tree |
UNTREEIFY_THRESHOLD | 6 | After rehashing, if tree nodes ≤ 6 → convert back to linked list |
The untreeify threshold is lower than treeify to prevent thrashing (repeatedly converting back and forth).
Full Bucket Evolution Diagram
12. Time Complexity of HashMap
Summary Table
| Operation | Average Case | Worst Case (old — linked list only) | Worst Case (modern — with treeify) |
|---|---|---|---|
put(key, value) | O(1) | O(N) | O(log N) |
get(key) | O(1) | O(N) | O(log N) |
remove(key) | O(1) | O(N) | O(log N) |
containsKey(key) | O(1) | O(N) | O(log N) |
remove(Object o) arbitrary | O(N) | O(N) | O(N) |
Why "Amortized O(1)"?
The occasional rehash operation costs O(N) (all entries must be moved). However, this happens very infrequently (only when threshold is crossed, and each rehash doubles the capacity). When averaged over all operations, the cost per operation approaches O(1). This is called amortized O(1).
13. HashMap Methods Full Reference with Examples
Complete Working Example
1import java.util.*;2
3public class HashMapDemo {4 public static void main(String[] args) {5
6 // --- SETUP ---7 HashMap<Integer, String> map = new HashMap<>();8
9 // put(key, value) — insert; overwrites if key exists10 map.put(null, "test"); // null key is allowed11 map.put(0, null); // null value is allowed12 map.put(1, "A");13 map.put(2, "B");14
15 // putIfAbsent(key, value) — only inserts if key absent OR value is null16 map.putIfAbsent(null, "newValue"); // null key EXISTS with value "test" (not null) → NO overwrite17 map.putIfAbsent(0, "zero"); // key 0 EXISTS but value IS null → OVERWRITES with "zero"18 map.putIfAbsent(3, "C"); // key 3 does NOT exist → INSERTS19
20 // --- QUERY METHODS ---21
22 // size() — number of key-value mappings23 System.out.println("Size: " + map.size()); // 524
25 // isEmpty() — true if no entries26 System.out.println("Is empty: " + map.isEmpty()); // false27
28 // containsKey(key)29 System.out.println("Contains key 3: " + map.containsKey(3)); // true30 System.out.println("Contains key 9: " + map.containsKey(9)); // false31
32 // get(key) — returns value or null if key absent33 System.out.println("Get key 1: " + map.get(1)); // A34
35 // getOrDefault(key, defaultValue)36 System.out.println("Get key 9 or default: " + map.getOrDefault(9, "N/A")); // N/A37
38 // --- REMOVAL ---39
40 // remove(key) — removes and returns the value41 String removed = map.remove(null);42 System.out.println("Removed null key, value was: " + removed); // test43
44 // --- ITERATION ---45
46 // entrySet() — iterate over key-value pairs47 System.out.println("\nAll entries (entrySet):");48 for (Map.Entry<Integer, String> entry : map.entrySet()) {49 System.out.println("Key: " + entry.getKey() + " | Value: " + entry.getValue());50 }51
52 // keySet() — iterate over keys only53 System.out.println("\nAll keys (keySet):");54 for (Integer key : map.keySet()) {55 System.out.println(key);56 }57
58 // values() — iterate over values only59 System.out.println("\nAll values (values()):");60 for (String value : map.values()) {61 System.out.println(value);62 }63 }64}Output
1Size: 52Is empty: false3Contains key 3: true4Contains key 9: false5Get key 1: A6Get key 9 or default: N/A7Removed null key, value was: test8
9All entries (entrySet):10Key: 0 | Value: zero11Key: 1 | Value: A12Key: 2 | Value: B13Key: 3 | Value: C14
15All keys (keySet):16017118219320
21All values (values()):22zero23A24B25CentrySet(), keySet(), and values() is unpredictable and may change between JVM runs.`putIfAbsent` Detailed Explanation
putIfAbsent(key, value) considers a key "absent" in two cases:
- The key does not exist in the map at all.
- The key exists but its current value is
null.
1map.put("x", null); // x → null2map.putIfAbsent("x", "hello"); // x is present but value is null → OVERWRITES → x → "hello"3
4map.put("y", "world");5map.putIfAbsent("y", "bye"); // y is present with non-null value → NO overwrite → y stays "world"6
7map.putIfAbsent("z", "new"); // z doesn't exist → INSERTS → z → "new"`entrySet()` vs `keySet()` vs `values()`
| Method | Returns | Use when |
|---|---|---|
entrySet() | Set | You need both key AND value |
keySet() | Set | You only need keys |
values() | Collection | You only need values |
entrySet(). Using keySet() and then calling get(key) inside the loop is less efficient — it performs an extra hash lookup per iteration.14. HashMap vs HashTable vs ConcurrentHashMap
Overview
HashMap has two thread-safe counterparts: HashTable (legacy) and ConcurrentHashMap (modern).
Comparison Table
| Feature | HashMap | HashTable | ConcurrentHashMap |
|---|---|---|---|
| Thread-safe | ❌ No | ✅ Yes (synchronized) | ✅ Yes (segment-level locking) |
| Null keys | ✅ 1 null key allowed | ❌ Not allowed | ❌ Not allowed |
| Null values | ✅ Allowed | ❌ Not allowed | ❌ Not allowed |
| Performance | Fast (no locking) | Slower (full lock) | Fast (partial locking) |
| Maintains order | ❌ No | ❌ No | ❌ No |
| Legacy? | No (modern) | Yes (legacy) | No (modern) |
| Recommended? | ✅ Single-threaded | ❌ Avoid | ✅ Multi-threaded |
Key Points
HashMap Not Thread-Safe
HashMap does not synchronize any of its methods. If two threads modify a HashMap concurrently without external synchronization, the behavior is undefined and can result in infinite loops, data corruption, or exceptions.
1// NOT safe in multi-threaded code:2Map<String, Integer> map = new HashMap<>();3// Thread 1: map.put("a", 1)4// Thread 2: map.put("b", 2) ← concurrent modification → undefined behaviorHashTable Synchronized but Legacy
HashTable synchronizes every method with a single lock on the entire object. While thread-safe, this means only one thread can access the table at a time — a major bottleneck in high-concurrency scenarios. HashTable is considered legacy and its use is discouraged in new code.
1// Thread-safe but slow — avoid in new code:2Map<String, Integer> table = new Hashtable<>();ConcurrentHashMap Modern Thread-Safe Choice
ConcurrentHashMap is the modern alternative. It uses segment-level (or bucket-level) locking in Java 8+, meaning multiple threads can read and write to different segments of the map simultaneously. It offers much better throughput than HashTable.
1// Recommended for multi-threaded code:2Map<String, Integer> concurrentMap = new ConcurrentHashMap<>();Inheritance Diagram
HashTable extends the old Dictionary abstract class (pre-Collections Framework) and also implements Map. This is a legacy design that predates the Java Collections Framework.15. Common Mistakes
Mistake 1 Using HashMap in Multi-threaded Code Without Synchronization
1// WRONG — concurrent modification may cause infinite loops or data loss2Map<String, Integer> map = new HashMap<>();3// Thread A and Thread B both call map.put() simultaneously → undefined behaviorFix: Use ConcurrentHashMap or wrap with Collections.synchronizedMap().
1Map<String, Integer> safeMap = new ConcurrentHashMap<>();2// OR:3Map<String, Integer> safeMap = Collections.synchronizedMap(new HashMap<>());Mistake 2 Overriding `equals()` Without Overriding `hashCode()`
1class Student {2 int id;3 Student(int id) { this.id = id; }4
5 @Override6 public boolean equals(Object o) {7 return ((Student) o).id == this.id;8 }9 // hashCode NOT overridden — uses default Object.hashCode() based on memory address10}11
12Map<Student, String> map = new HashMap<>();13map.put(new Student(1), "Alice");14System.out.println(map.get(new Student(1))); // null! Different object → different hash → wrong bucketFix: Always override both equals() and hashCode() together.
1@Override2public int hashCode() {3 return Integer.hashCode(this.id);4}Mistake 3 Expecting HashMap to Maintain Insertion Order
1Map<Integer, String> map = new HashMap<>();2map.put(3, "C");3map.put(1, "A");4map.put(2, "B");5map.entrySet().forEach(System.out::println); // Order is NOT guaranteedFix: Use LinkedHashMap to maintain insertion order, or TreeMap for sorted order.
1Map<Integer, String> ordered = new LinkedHashMap<>();Mistake 4 Iterating and Modifying a HashMap Simultaneously
1for (Map.Entry<Integer, String> entry : map.entrySet()) {2 map.remove(entry.getKey()); // ❌ ConcurrentModificationException3}Fix: Use an Iterator with iterator.remove(), or collect keys to remove first.
1Iterator<Map.Entry<Integer, String>> it = map.entrySet().iterator();2while (it.hasNext()) {3 Map.Entry<Integer, String> entry = it.next();4 if (entry.getKey() == 2) {5 it.remove(); // ✅ safe removal during iteration6 }7}Mistake 5 Using Mutable Objects as Keys
1List<Integer> key = new ArrayList<>(Arrays.asList(1, 2, 3));2map.put(key, "value");3key.add(4); // Mutating the key changes its hashCode → get() can never find it again4System.out.println(map.get(key)); // null — key's bucket has changedFix: Only use immutable objects as HashMap keys (String, Integer, Long, etc.).
16. Best Practices
- Always override both
equals()andhashCode()when using custom objects as keys. - Prefer immutable keys —
String,Integer,Long, enums are safe choices. - Use
ConcurrentHashMapin multi-threaded environments instead ofHashMaporHashTable. - Pre-size the HashMap if you know the approximate number of entries to avoid rehashing:
1 // For 100 expected entries, set initial capacity to avoid rehashing at 75:2 Map<String, Integer> map = new HashMap<>(150);- Use
entrySet()for iteration when you need both key and value — neverkeySet()+get()in a loop. - Don't use
HashTablein new code — it's legacy. UseConcurrentHashMapfor thread-safety. - Check
containsKey()beforeget()when null values are possible, to distinguish "key absent" from "key present with null value".
17. Interview Notes
Q1: How does HashMap work internally?
Answer: HashMap stores data in an array of Node objects (called the hash table). When put(key, value) is called: (1) the hash of the key is computed, (2) the index is computed as hash mod tableSize, (3) the node is placed at that index. If a collision occurs (another node already at that index with a different key), the new node is chained as a linked list. If the chain length reaches 8, it converts to a Red-Black Tree. When get(key) is called, the same hash computation finds the right bucket, then the chain is traversed using equals() to find the exact node.
Q2: What is the time complexity of HashMap operations?
Answer: Average case O(1) for put, get, and remove. Worst case is O(log N) in Java 8+ (due to treeify), not O(N) as in older versions. The O(1) average is amortized — occasional rehash operations cost O(N) but are rare.
Q3: What is the default initial capacity and load factor of HashMap?
Answer: Default initial capacity is 16. Default load factor is 0.75. The rehash threshold is 16 × 0.75 = 12, meaning rehashing occurs after the 12th entry is inserted.
Q4: What is the difference between HashMap and HashTable?
Answer: HashMap is not thread-safe and allows one null key and null values. HashTable is thread-safe (fully synchronized) and does not allow null keys or values. HashTable is legacy — prefer ConcurrentHashMap in new multi-threaded code.
Q5: What is the contract between `hashCode()` and `equals()`?
Answer: Two rules: (1) If two objects are equal (equals() returns true), they MUST have the same hashCode(). (2) If two objects have the same hashCode(), they are NOT necessarily equal. Violating rule 1 breaks HashMap — get() will fail to find entries.
Q6: What happens when you put a duplicate key in a HashMap?
Answer: The value is overwritten. The map always has at most one entry per key. put() returns the old value that was replaced.
Q7: Can HashMap have null keys?
Answer: Yes — HashMap allows exactly one null key. Internally, the null key is stored at index 0 of the array (since hashCode(null) = 0).
Q8: What is rehashing?
Answer: When the number of entries exceeds capacity × loadFactor, HashMap allocates a new array of double the size and re-inserts all existing entries by recomputing their indices. This redistributes entries across more buckets, reducing collision chains and restoring O(1) average performance.
Q9: When does HashMap convert a linked list to a tree?
Answer: When the number of nodes in a single bucket reaches the treeify threshold of 8, the linked list is converted to a Red-Black Tree, improving worst-case search from O(N) to O(log N). If after a rehash the nodes in a tree bucket fall to 6 or below, it converts back to a linked list.
Q10: What is `Map.Entry`?
Answer: Map.Entry is a nested interface inside Map that represents a single key-value pair. HashMap implements it as the Node class. It is returned by entrySet() and provides getKey() and getValue() methods for accessing the pair's data.
Tricky Points
HashTableis spelled with a lowercase 't' inTable—Hashtable. Common spelling error.HashMapallows one null key butConcurrentHashMapandHashtabledo not.- Printing a
HashMapdirectly callstoString()which iteratesentrySet()— the order is NOT insertion order. put()returns the previous value for an existing key, ornullif the key was absent (or if the previous value wasnull).- Using
getOrDefault()is safer thanget()when you want to handle missing keys — no null check needed. - The
keySet()returned by HashMap is a live view — modifying the map while iteratingkeySet()causesConcurrentModificationException.
18. Practice Questions
Easy
- Create a
HashMaprepresenting word frequencies. Insert five words and print each word with its count. - What is the default initial capacity of a
HashMap? - What is the difference between
get(key)andgetOrDefault(key, defaultValue)? - Can a
HashMaphave two entries with the same value but different keys? Show with an example. - What does
putIfAbsent()do if the key already exists with a non-null value?
Medium
- Explain what happens step-by-step when you call
put("hello", 42)on aHashMap. - You override
equals()in your custom class but forget to overridehashCode(). What happens when you use it as a key inHashMap? Why? - When and why does HashMap convert a bucket's linked list to a Red-Black Tree?
- Write a method that counts the frequency of each character in a string using
HashMap. - What is the difference between iterating with
keySet()vsentrySet()? Which is more efficient and why?
Hard
- Design a HashMap from scratch in Java. Implement
put(key, value)andget(key)with collision handling via separate chaining. - What happens during rehashing? Walk through the rehash process for a
HashMapthat has grown from initial capacity 16 to 32. - Explain why the initial capacity is always a power of 2 in
HashMap. What optimization does this enable? - Compare
HashMap,LinkedHashMap, andTreeMapon time complexity forput,get, and iteration. When would you use each? - A
HashMapis created and a mutable- , String>
Listis used as a key. After inserting an entry, the list is modified. What happens when you try to retrieve the value? Explain why, at the byte-code level.
19. Summary Revision Bullets
Why Map is Separate from Collection
Collectionworks with single values;Mapworks with key-value pairs.- All
Collectionmethods are single-value oriented — incompatible with Map's two-value API. Mapis a completely independent interface hierarchy injava.util.
Map Key Properties
- No duplicate keys; duplicate values allowed.
- Inserting a duplicate key overwrites the existing value.
- One null key allowed in
HashMap; null values allowed.
HashMap Internals
- Backed by an array of Node objects (the hash table).
- Default array size: 16; load factor: 0.75; rehash threshold: 12.
- Each
Nodestores:hash,key,value,next. - Index formula:
hash mod tableSize.
put() Process
- Compute
hashCode(key). - Compute
index = hash mod tableSize. - If bucket empty: insert new Node.
- If collision: check
hash + equalsfor duplicate key → overwrite or chain. - If chain length reaches 8: convert to Red-Black Tree.
get() Process
- Compute
hashCode(key)→ same index as duringput. - Traverse chain at that index.
- Match using
hash == node.hash && key.equals(node.key). - Return
node.valueon match;nullif not found.
hashCode/equals Contract
- Equal objects MUST have equal hash codes.
- Equal hash codes do NOT imply equal objects.
- Must override both together when using custom objects as keys.
Load Factor & Rehashing
- Load factor (default 0.75) controls when to resize.
- Threshold crossed → array doubles → all entries rehashed.
- Prevents long chains; restores average O(1) performance.
Treeify Threshold
- Chain length ≥ 8 → linked list converts to Red-Black Tree.
- Reduces worst-case from O(N) to O(log N).
- Untreeify at ≤ 6 nodes after rehash.
Time Complexity
- Average: O(1) for all major operations (amortized).
- Worst case: O(log N) in Java 8+ (Red-Black Tree).
HashMap vs HashTable vs ConcurrentHashMap
HashMap: not thread-safe, allows null key/value, modern standard.HashTable: thread-safe (legacy), no nulls, avoid in new code.ConcurrentHashMap: thread-safe (modern), no nulls, preferred for concurrency.
End of Chapter — Map Interface & HashMap Internals
Practice & Implement
Apply what you learned in HashMap Internals
Count word frequency in a sentence and print the top 2 most frequent words sorted by count descending, then alphabetically for ties.
fox: 2 the: 2
Mastery check
How well can you recall this?
Finished this lesson?