Skip to content

Commit 6c77fd6

Browse files
Update HashMapDemo.java
1 parent dc38ae9 commit 6c77fd6

File tree

1 file changed

+49
-1
lines changed

1 file changed

+49
-1
lines changed

src/learnCollections/HashMapDemo.java

Lines changed: 49 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -65,9 +65,57 @@ When we call get(key), the HashMap follows these steps:
6565
- Once the correct bucket is found, it checks for the key in that bucket. If it finds the key, it returns the associated value
6666
*/
6767

68+
69+
/*
70+
+-----+-----+-----+-----+-----+
71+
| 0 | 1 | 2 | 3 | 4 |
72+
+-----+-----+-----+-----+-----+
73+
|
74+
v
75+
+-----------+
76+
| (k1, v1) |
77+
+-----------+
78+
|
79+
v
80+
+-----------+
81+
| (k2, v2) |
82+
+-----------+
83+
|
84+
v
85+
null
86+
87+
88+
class Node<K, V> {
89+
final int hash; // hash code of the key
90+
final K key; // the key itself
91+
V value; // the value associated with the key
92+
Node<K, V> next; // pointer to the next node in case of a collision (linked list)
93+
}
94+
95+
96+
This searching in linked list is O(n) time complexity in worst case (when all keys hash to the same bucket).
97+
To mitigate this, Java 8 introduced a Balanced BST (Red-Black Tree - Self balancing BST) -> O(log n).
98+
TREEIFY_THRESHOLD = 8 (when a bucket has more than 8 entries, it converts the linked list to a tree for better performance)
99+
*/
100+
101+
102+
/*
103+
HashMap Resizing (Rehashing):
104+
105+
- HashMap has an internal array size, which by default is 16.
106+
When the no. of elements (key-value pairs) exceeds a certain threshold (load factor, default is 0.75), the HashMap automatically resizes the array to hold more data. This process is called rehashing.
107+
108+
- The default size of the array is 16, so when more than 12 elements (16 * 0.75) are inserted, the HashMap will resize.
109+
110+
During Rehashing:
111+
- The array size is doubled.
112+
1. All existing entries are rehashed (i.e. their positions are recalculated) and placed into the new array
113+
2. This ensures the HashMap continues to perform efficiently even as more data is added
114+
*/
115+
68116
public class HashMapDemo {
69117
public static void main(String[] args) {
70-
HashMap<Integer, String> map = new HashMap<>();
118+
HashMap<Integer, String> map = new HashMap<>(17, 0.5f); // initial capacity = 17, load factor = 0.5
71119
map.put(3, "Prateek");
72120
map.put(1, "Rahul");
73121
map.put(2, "Mayank");

0 commit comments

Comments
 (0)