You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: src/learnCollections/HashMapDemo.java
+49-1Lines changed: 49 additions & 1 deletion
Original file line number
Diff line number
Diff line change
@@ -65,9 +65,57 @@ When we call get(key), the HashMap follows these steps:
65
65
- Once the correct bucket is found, it checks for the key in that bucket. If it finds the key, it returns the associated value
66
66
*/
67
67
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
0 commit comments