Java HashMap Internals
Content
- What is HashMap?
- Internal Data Structure
- How
put()Works - How
get()Works - Hash Calculation
- Bucket Index Calculation
- Collision Handling
- Resizing and Rehashing
equals()vshashCode()- Java Keywords in HashMap
- Null Keys and Values
- Time and Space Complexity
- HashMap vs ConcurrentHashMap
- Java 7 vs Java 8 vs Java 17/21
What is HashMap?
A HashMap in Java stores data as key-value pairs. Each key is unique and is used to find its corresponding value.
Map<Integer, String> employees = new HashMap<>();
employees.put(101, "Alice");
employees.put(102, "Bob");
employees.get(101); // "Alice"When we call get(101), HashMap doesn't search through every employee. Instead, it uses hashing.
Hashing means converting a key into a number called a hash code. HashMap uses this number to calculate an index in an internal array. Each position in that array is called a bucket.
This is why put(), get(), and remove() take O(1) time on average. HashMap can usually locate the correct bucket directly, regardless of how many entries it contains.
However, multiple keys can map to the same bucket. This is called a hash collision. HashMap must then compare keys within that bucket, which can make operations slower.
Internal Data Structure
Internally, a HashMap uses an array called table to store key-value pairs.
Node<K,V>[] table;Each position in the array is called a bucket. Each bucket can hold multiple entries, represented by Node objects.
static class Node<K,V> {
final int hash;
final K key;
V value;
Node<K,V> next;
}Each node stores the key, value, hash, and a reference to the next node.
When multiple keys land in the same bucket, a collision occurs. HashMap stores these nodes in a linked list, which can become a red-black tree if the list grows too long.
Capacity is the number of buckets, not the number of entries. The default initial capacity is 16, and the load factor is 0.75. So, when the 13th entry is inserted, HashMap normally doubles its capacity to 32 to keep lookups efficient.
How put() Works
When we call put(key, value), HashMap finds the correct bucket and stores the entry there.
map.put(101, "Alice");First, HashMap calls key.hashCode() and mixes its bits to calculate a better-distributed hash.
It then calculates the bucket index using:
index = (capacity - 1) & hash;Here, & is bitwise AND. It selects an index between 0 and capacity - 1.
Once the bucket is found:
- Empty bucket: Insert a new node.
- Same key exists: Replace its value using
equals()to identify the key. - Different keys in the same bucket: A collision occurs. Add a node to the linked list, or insert into the red-black tree if the bucket is tree-based.
Finally, HashMap checks whether its size exceeds the resize threshold. If it does, the internal array grows, normally doubling its capacity.
Time complexity: O(1) on average for insertion.
How get() Works
When we call get(key), HashMap uses the key to find its stored value.
map.get(101); // "Alice"First, HashMap calls key.hashCode() and mixes its bits to calculate the hash. It then finds the bucket index using:
index = (capacity - 1) & hash;Once the bucket is found, HashMap compares the stored keys.
- Hash matches: Check whether the keys are identical (
==) or equal (equals()). - Key matches: Return its value.
- Key doesn’t match: Search the remaining nodes in the linked list or red-black tree.
- No matching key: Return
null.
Why both hashCode() and equals()? hashCode() helps locate the bucket, while equals() confirms the correct key. Different keys can have the same hash.
Time complexity: O(1) on average, O(log n) for a tree-based bucket, and O(n) in the worst case for a linked-list bucket.
Hash Calculation
HashMap uses hashCode() to get a 32-bit integer from the key. It then spreads the hash bits to distribute keys more evenly across buckets.
int h = key.hashCode();
int hash = h ^ (h >>> 16);Here:
hashCode()returns a 32-bit integer representing the key.>>> 16shifts the bits 16 positions to the right, filling the left side with zeros.^(XOR) compares two bits: it returns1if they differ and0if they match.
A 32-bit hash has two halves: the upper 16 bits and the lower 16 bits.
Simplified 8-bit example: shifting by 4 instead of 16
Why spread the bits? HashMap uses the lower bits of the hash to select a bucket. If two hashes have identical lower bits but different upper bits, they could land in the same bucket.
XOR mixes information from the upper bits into the lower bits, helping reduce collisions.
The resulting hash is then used to calculate the bucket index:
index = (capacity - 1) & hash;Bucket Index Calculation
HashMap uses the calculated hash to find which bucket should store the key.
index = (n - 1) & hash;Here, n is the array capacity, and & is bitwise AND. It returns 1 only when both corresponding bits are 1.
For example, suppose the capacity is 16 and the hash is 27.
n - 1 = 15 → 01111
hash = 27 → 11011
-----
AND 01011 → 11So the entry goes into bucket 11.
Why must capacity be a power of two? With a capacity of 16, n - 1 is 15 (1111 in binary). This lets HashMap use the lowest 4 bits of the hash to select an index from 0 to 15.
Because capacities are powers of two, HashMap can use fast bitwise AND instead of the modulo operation (hash % n).
Collision Handling
A hash collision occurs when two different keys map to the same bucket.
HashMap handles collisions by storing multiple entries in that bucket.
Get Himani Prasad’s stories in your inbox
Join Medium for free to get updates from this writer.
Initially, entries form a linked list, where each node points to the next node. To find a key, HashMap checks the nodes until it finds a match.
If too many entries accumulate in one bucket, HashMap can convert the linked list into a Red-Black Tree, making lookups faster.
Java 8 and later use these thresholds:
- 8 nodes (
TREEIFY_THRESHOLD): Treeification is triggered when inserting into a bucket that already has at least 8 nodes. - 64 buckets (
MIN_TREEIFY_CAPACITY): The table must have at least 64 buckets for treeification. Otherwise, HashMap resizes instead. - 6 nodes (
UNTREEIFY_THRESHOLD): A tree can convert back into a linked list when its node count becomes small enough.
Time complexity: Linked-list lookup takes O(n) in the worst case, while a Red-Black Tree provides O(log n) lookup for its ordered tree operations.
Treeification prevents heavily populated buckets from making HashMap operations unnecessarily slow.
Resizing and Rehashing
As more entries are inserted, HashMap may need to resize its internal array to keep lookups efficient.
By default, HashMap uses:
- Capacity: 16 buckets initially.
- Load factor: 0.75, which controls when resizing happens.
- Threshold: Capacity × Load Factor = 16 × 0.75 = 12.
When the 13th entry is inserted, HashMap normally doubles its capacity from 16 to 32.
But increasing the array size isn’t enough. HashMap must also redistribute existing nodes, because their bucket indices may change.
oldIndex = (16 - 1) & hash;
newIndex = (32 - 1) & hash;For example, a key with hash 21 moves from bucket 5 to bucket 21.
In Java 8 and later, HashMap optimizes this process. When capacity doubles, each node either stays in its original bucket or moves to oldIndex + oldCapacity. It doesn't need to recalculate the key's hashCode().
Resizing takes O(n) time because existing entries must be redistributed, but it happens occasionally, so insertion remains O(1) on average (amortized).
equals() vs hashCode()
HashMap uses both hashCode() and equals() to identify keys, but they serve different purposes.
hashCode()helps HashMap find the correct bucket.equals()checks whether two keys represent the same logical key.
The contract: If two objects are equal according to equals(), they must return the same hashCode(). However, two different objects can have the same hash code.
When inserting a key, HashMap checks whether an equal key already exists. If it does, the existing value is replaced, rather than creating a duplicate entry.
map.put("Alice", 100);
map.put("Alice", 200);
map.get("Alice"); // 200
map.size(); // 1Why are mutable keys dangerous?
Suppose an object is used as a key, and one of its fields contributes to hashCode(). If that field changes after insertion, the calculated bucket may change.
HashMap doesn’t automatically move the existing entry, so get() may fail to find it.
Best practice: Use immutable keys, such as String, Integer, or immutable custom objects, and override equals() and hashCode() together when defining logical equality.
Java Keywords in HashMap — transient, static, final, and their purpose
Java’s HashMap uses transient, static, and final to control how its internal data is stored and accessed.
transient Node<K,V>[] table;
static class Node<K,V> {
final int hash;
final K key;
V value;
Node<K,V> next;
}transient — Excludes a field from default serialization.
The internal table is not serialized directly. HashMap uses custom serialization to save its entries and reconstruct the table during deserialization.
static — Makes Node independent of a HashMap instance.
Node is a static nested class, so each node doesn't need an implicit reference to its enclosing HashMap object. We can still create Node objects.
final — Prevents reassignment after initialization.
The key and hash cannot be changed after the node is created. However, value can change when put() updates an existing entry.
These keywords help HashMap manage memory, preserve key information, and control serialization.
Null Keys and Values
Java’s HashMap allows one null key and multiple null values.
map.put(null, "Alice");
map.put(101, null);
map.put(102, null);How does a null key work?
Normally, HashMap calls key.hashCode() to calculate a hash. But calling a method on null would throw a NullPointerException.
So HashMap handles it separately:
hash = (key == null) ? 0 : spread(key.hashCode());A null key always has hash 0, so it is stored in bucket 0. Other keys can also occupy this bucket.
What about null values?
HashMap stores them like ordinary values. However, get() returns null both when a key is missing and when its value is null.
Use containsKey() to distinguish between these cases.
map.get(101); // null
map.containsKey(101); // trueInserting another null key replaces the existing null-key entry's value because HashMap permits only one entry per key.
Time and Space Complexity
HashMap provides O(1) average time complexity because hashing lets it find the correct bucket directly, without searching through every entry.
put(): avgO(1), worstcase: O(n)
get():O(1), O(n)
remove(): O(1), O(n)
containsKey():O(1), O(n)
Why O(n) in the worst case? If many keys collide and form a linked list, HashMap may need to examine every node. With a tree-based bucket, searching takes O(log n).
Why can put() take O(n)? Resizing requires redistributing existing entries into a larger array. However, resizing happens occasionally, so insertion remains O(1) on average (amortized).
Space complexity: O(n) for storing n entries, assuming the table capacity stays proportional to the number of entries.
HashMap is efficient when keys have well-distributed hash codes, keeping collisions low.
HashMap vs ConcurrentHashMap
Both HashMap and ConcurrentHashMap store key-value pairs, but the main difference is thread safety.
HashMap is not thread-safe. If multiple threads modify it simultaneously, updates can be lost, and its internal structure can become inconsistent.
ConcurrentHashMap is thread-safe. It allows multiple threads to read and update the map concurrently without corrupting its internal data.
How does ConcurrentHashMap work?
In Java 8 and later, ConcurrentHashMap uses CAS (Compare-And-Swap) for some updates and locks individual buckets when necessary, rather than locking the entire map.
For example, if two threads update entries in different buckets, they can usually proceed simultaneously.
One important detail: although individual operations like put() and get() are thread-safe, a sequence such as get() followed by put() is not automatically atomic. Use methods like compute() or putIfAbsent() when the combined operation must be atomic.
When to use which? Use HashMap for single-threaded access or externally synchronized access. Use ConcurrentHashMap when multiple threads need to access and modify the same map concurrently.
Java 7 vs Java 8 vs Java 17/21
HashMap’s biggest internal change happened in Java 8. Java 17 and 21 largely retain the same implementation.
Why did Java 8 introduce Red-Black Trees?
In Java 7, if many keys landed in the same bucket, HashMap stored them in a linked list. Finding a key could require checking every node, taking O(n) time.
Java 8 introduced treeification. When a bucket becomes heavily populated and the table has at least 64 buckets, HashMap can convert the linked list into a red-black tree, improving lookup performance.
What changed in Java 17 and 21?
There were no major changes to HashMap’s core data structure. They still use hashing, linked lists, red-black trees, and power-of-two capacities.
The key difference: Java 7 relies entirely on linked lists for collisions, while Java 8 and later can use trees to handle heavy collisions more efficiently.
*O(log n) applies to tree-based lookup; overall worst-case behavior also depends on key comparison and hash distribution.








