Java Hashmap Under The Hood -
Under the hood, a Java HashMap is a combination of an node objects (linked lists or trees) that uses to store and retrieve data in average time. 1. The Core Structure: Array of Buckets Internally, a HashMap maintains an array called a . Each slot in this array is known as a Default Capacity : Usually starts at 16. Node Storage : Each bucket stores a object containing four fields: the to the next node. put(key, value) When you add an entry, the JVM follows these steps: Calculate Hash : It calls the key's hashCode() method to generate an integer. Determine Index : It applies a hash function (often hash % array_length
table (length=16) [0] -> null [1] -> Node(key=apple, hash=...) -> Node(key=apricot, ...) [2] -> TreeNode (if many collisions) ...
// putVal() method to add a new entry to the map final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) // ... java hashmap under the hood
Searching in a linked list is O(n) . If thousands of keys land in the same bucket (due to a poor hash function or malicious input), your "constant-time" HashMap becomes a linear-time disaster.
A HashMap consists of the following components: Under the hood, a Java HashMap is a
Since Java 8, if a bucket exceeds a , it converts to a Balanced Tree (Red-Black Tree) to improve performance from
: Defaults to 0.75 . It determines how full the map can get before resizing. Each slot in this array is known as
The HashMap that linked list into a Red-Black Tree (an implementation of TreeNode ).
float loadFactor = 0.75f; // default int threshold = (int) (capacity * loadFactor);
: The hash is mapped to an array index using (n - 1) & hash , where n is the array length.
When the following conditions are met: