Calling put() on a Java HashMap looks simple. You pass a key and a value, and the method stores the entry. Internally, however, Java calculates a hash, selects a bucket, checks for duplicate keys, and handles collisions before completing the operation.
Understanding Hashmap Internal Working helps when you are building caches, handling application data or investigating unexpected lookup results. For example, a poorly implemented hashCode() method can make an entry difficult to retrieve even when the key appears identical.
Map<String, String> cache = new HashMap<>();
cache.put("user_101", "Active");
The important part is what happens between these two lines of code. This guide explains the bucket structure, hashing mechanism, put(), get(), remove(), resizing and the differences between HashMap and ConcurrentHashMap.
What Is Java HashMap and Why Use It?
The HashMap class belongs to the java.util package and implements the Map<K,V> interface in the Java Collections Framework. It stores information as key-value pairs. Keys must be unique, but values can be duplicated.
A HashMap has a few important characteristics:
- It permits one null key and multiple null values.
- It does not guarantee insertion or sorted order.
- It is not synchronized and is not thread-safe.
- Its basic get() and put() operations offer average O(1) performance when hashes are distributed properly.
HashMap is useful for in-memory caches, configuration storage, session data and frequency counting. If you need sorted keys, TreeMap is a better option, although its basic operations generally take O(log n). LinkedHashMap maintains a predictable iteration order, with additional memory overhead.
HashMap is also connected to other Java collection concepts. A HashSet, for example, uses a HashMap internally to store its elements as keys. If you are unfamiliar with the type parameters used in Map<K,V>, this introduction to Java Generics explains how they provide compile-time type safety.
How Does HashMap Actually Work Internally?
HashMap stores entries in an internal array commonly called table. Each position in this array is a bucket. An entry is represented by a Node<K,V> object containing four main fields:
static class Node<K,V> {
final int hash;
final K key;
V value;
Node<K,V> next;
}
The hash field stores the processed hash value, key and value hold the mapping, and next points to another node when multiple entries occupy the same bucket.
A simplified bucket structure looks like this:
table Array (Buckets)
[0] -> null
[1] -> Node(A, Data1)
-> Node(B, Data2)
-> null
[2] -> null
[3] -> Node(C, Data3)
-> null
When two keys map to the same bucket, HashMap connects their nodes through the next reference. This structure is called separate chaining.
How Does HashMap Calculate the Hash?
When you insert or retrieve a key, HashMap calls its hashCode() method. The returned value is a 32-bit integer, which Java processes before using it to select a bucket.
In Java 8 and later, the hash-spreading operation is:
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
The unsigned right shift moves the upper 16 bits down, and the XOR operation mixes them with the original hash. This helps distribute information from higher-order bits into the lower bits used during bucket selection.
How Is the Bucket Index Calculated?
HashMap maintains its table capacity as a power of two, such as 16, 32 or 64. It uses the following expression to calculate the bucket index:
index = (n - 1) & hash;
Here, n is the table capacity and hash is the processed hash value. The bitwise AND operation produces an index within the valid bucket range.
This should not be described as universally identical to Java's signed % remainder operation for negative hash values. The bitwise mask is used because the table capacity is a power of two and the resulting index is non-negative.
How Do put(), get(), and remove() Work?
These three methods handle the main operations performed on a HashMap.
HashMap<String, Integer> inventory = new HashMap<>();
inventory.put("SKU-992", 450);
Integer stock = inventory.get("SKU-992");
inventory.remove("SKU-992");
How Does put() Insert an Entry?
When you call put(key, value), HashMap follows a sequence of checks before storing the entry. The simplified execution flow is shown below.
flowchart TD
A["put(key, value)"] --> B["Calculate spread hash"]
B --> C["Initialize table if required"]
C --> D["Calculate bucket index"]
D --> E{"Is bucket empty?"}
E -->|Yes| F["Create and insert Node"]
E -->|No| G{"Does key already exist?"}
G -->|Yes| H["Replace existing value"]
G -->|No| I{"Is bucket a tree?"}
I -->|Yes| J["Insert through tree logic"]
I -->|No| K["Traverse linked list"]
K --> L["Append new Node"]
J --> M["Update size and check threshold"]
F --> M
L --> M
M --> N["Resize if threshold is exceeded"]
H --> O["Return previous value"]
N --> P["Complete insertion"]
The key steps are:
- Hash calculation: HashMap calculates the processed hash of the key.
- Table initialization: If the internal array has not been allocated, it initializes the table.
- Bucket selection: It calculates the target index using (n - 1) & hash.
- Key comparison: If the bucket is occupied, it compares the stored hash and checks key identity or equals().
- Collision handling: It searches the linked list or uses the tree structure if the bucket has been converted.
- Insertion or replacement: An existing key has its value updated. A new key increases the map's size.
- Resize check: If the size exceeds the threshold, HashMap expands the table.
You can compare this process with the HashMap question covered in Java coding interview questions, where internal collection behaviour is a common technical interview topic.
How Does get() Retrieve a Value?
The get(key) method calculates the same processed hash and bucket index used during insertion. It then checks the first node in that bucket.
- If the hash and key match, it returns the value.
- If the bucket contains a linked list, it checks subsequent nodes using hash and equality comparisons.
- If the bucket contains a tree, it searches through the tree structure.
- If no matching key is found, it returns null.
A null return does not always mean that the key is absent. HashMap permits null values, so containsKey() can help distinguish between a missing key and a key explicitly mapped to null.
How Does remove() Delete an Entry?
The remove(key) method locates the entry using its hash and key comparison. Once it finds the node, HashMap removes it from the bucket.
- If it is the first node, the bucket points to the next node.
- If it is in the middle of a linked list, the previous node skips over it.
- If it belongs to a tree bin, the tree structure is adjusted as required.
The map's size decreases after removal. HashMap does not automatically shrink its table whenever entries are deleted.
How Does HashMap Handle Collisions?
A collision occurs when two different keys map to the same bucket index. HashMap handles this through separate chaining, storing multiple nodes in the same bucket.
In Java 8 and later, a heavily populated linked-list bucket can be converted into a Red-Black tree. The implementation uses a treeification threshold of 8 and a minimum table capacity of 64. If the table is smaller than that capacity, HashMap resizes instead of immediately converting the bucket.
Tree bins help reduce lookup time when collisions become excessive. A linked-list bucket can require O(k) traversal, where k is the number of nodes, while a balanced tree can provide logarithmic search behaviour under suitable conditions.
For a practical overview of how this topic appears in technical rounds, see Top 50 Java Interview Questions and Answers.
How Does HashMap Resize and Use Load Factor?
HashMap uses two important parameters to decide when to expand its internal array:
- Capacity: The number of buckets available in the table. The default initial capacity is 16.
- Load factor: A measure of how full the table can become before resizing. The default value is 0.75.
The threshold is calculated as:
Threshold = Capacity × Load Factor
= 16 × 0.75
= 12
When the number of entries exceeds this threshold, HashMap resizes the table. With the default settings, inserting the 13th distinct entry triggers expansion from 16 to 32 buckets.
What Happens During Java 8 Resizing?
When capacity doubles, an existing node either stays at its current bucket index or moves by the old capacity. HashMap checks one additional bit in the processed hash:
(e.hash & oldCap) == 0
- If the result is zero, the node stays at its previous index.
- If the result is non-zero, it moves to oldIndex + oldCap.
This avoids recalculating the original key hash codes during the redistribution process.
A load factor of 0.75 balances memory use and collision frequency. A higher value can reduce unused bucket space but may increase collisions, while a lower value expands the table earlier and uses more memory. The Oracle HashMap API documentation explains how capacity and load factor affect performance and resizing.
Why Is ConcurrentHashMap Different?
HashMap is not designed for unsynchronized concurrent updates. If multiple threads modify the same map without suitable coordination, the application can experience inconsistent results.
ConcurrentHashMap is designed for concurrent access. Before Java 8, it used segmented locking. Modern implementations use a combination of Compare-And-Swap (CAS) operations and synchronized blocks around individual bins, allowing updates to different buckets to proceed with less contention.
Some important differences include:
- Null handling: HashMap permits one null key and null values. ConcurrentHashMap does not permit either.
- Iteration: HashMap iterators are fail-fast on a best-effort basis. ConcurrentHashMap iterators are weakly consistent and can tolerate concurrent updates; they do not provide a fixed snapshot.
- Concurrent access: ConcurrentHashMap supports multiple threads accessing and updating the map under its concurrency model.
If you are working with shared application data, understanding Java multithreading and concurrency helps explain why choosing the correct collection matters.
What Are Common HashMap Coding Mistakes?
Some HashMap problems come from incorrect assumptions about keys rather than the collection itself.
Breaking the equals() and hashCode() Contract
Java requires two objects that are equal according to equals() to return the same hash code. The reverse is not required: two objects can have the same hash code and still be unequal.
Consider this example:
class AccountKey {
private final String accountId;
AccountKey(String accountId) {
this.accountId = accountId;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (!(obj instanceof AccountKey)) return false;
AccountKey other = (AccountKey) obj;
return Objects.equals(accountId, other.accountId);
}
// hashCode() is missing
}
Now insert and retrieve an account:
Map<AccountKey, String> accounts = new HashMap<>();
accounts.put(new AccountKey("ACC-01"), "Checking");
String type = accounts.get(new AccountKey("ACC-01"));
The lookup can return null because the two separate objects may produce different default hash codes. The default Object.hashCode() is JVM-dependent and is not guaranteed to represent an object's memory address.
How would you debug this? First, check whether the two key objects return the same result from equals(). Then inspect their hashCode() values. If the values differ, implement hashCode() using the same field used by equals():
@Override
public int hashCode() {
return Objects.hash(accountId);
}
Run the lookup again with a newly created key. It should now locate the existing mapping. This is a useful debugging test when a map contains an entry but a lookup unexpectedly returns null.
Using Mutable Objects as Keys
Changing a field that contributes to a key's hash code after insertion can make the entry difficult to retrieve. The node remains in the bucket selected using its earlier hash, while a later lookup uses the updated hash.
Use immutable key objects wherever possible. Fields involved in equals() and hashCode() should not change while the object is being used as a map key.
What Is the Time Complexity of HashMap?
HashMap performance depends on how keys are distributed across buckets and how many collisions occur.
Operation
Average case
Collision-heavy case
put()
O(1)
O(k) for a list bucket
get()
O(1)
O(k) for a list bucket
remove()
O(1)
O(k) for a list bucket
Resize
O(n)
O(n)
Tree bins can improve searches in heavily populated buckets. These are implementation-level expectations, not guarantees that every operation will always take constant time.
For the implementation details, consult the OpenJDK Java 17 HashMap source code. It shows the actual putVal(), resize() and treeifyBin() methods used by that JDK version.
Frequently Asked Questions About Java HashMap
What is the internal working of Java HashMap?
HashMap stores key-value pairs in an array of buckets. It calculates a hash for each key, uses that value to select a bucket and stores the entry as a node. If multiple keys select the same bucket, they are connected through a linked list or stored in a tree bin when the relevant conditions are met.
How does HashMap work internally in Java 8?
Java 8 introduced tree bins for heavily populated buckets. Instead of relying only on linked lists, HashMap can convert a bucket into a Red-Black tree when its treeification conditions are met. It also uses a bitwise split during resizing to redistribute nodes.
What is the internal working of HashMap in Java 17?
Java 17 retains the core HashMap design used in Java 8: an array of buckets, processed hash values, linked-list collision handling and Red-Black tree bins. The exact implementation can be checked in the JDK 17 source code.
How does HashMap work internally with an example?
When you run map.put("A", 100), Java calculates the key's hash, selects a bucket and stores a node containing the key and value. When you call map.get("A"), it calculates the bucket again and checks the stored key using identity or equals().
What is the difference between HashMap and ConcurrentHashMap internally?
HashMap is not synchronized and is unsuitable for uncontrolled concurrent updates. ConcurrentHashMap uses concurrency mechanisms such as CAS operations and synchronized bin-level updates to support concurrent access. It also rejects null keys and values and provides weakly consistent iterators.
How does ConcurrentHashMap work internally in Java?
Modern ConcurrentHashMap implementations use an internal bucket array, CAS operations for certain updates and synchronized blocks when working with occupied bins. Reads are designed to proceed without locking in common cases, while its iteration behaviour tolerates concurrent changes.
Why does HashMap use a load factor of 0.75?
The default load factor of 0.75 balances bucket memory usage and collision frequency. A lower value can reduce collisions but causes earlier resizing, while a higher value can save bucket space at the cost of more collisions.
Why does HashMap use both hashCode() and equals()?
hashCode() helps HashMap locate the likely bucket. equals() checks whether a key in that bucket is actually equal to the requested key. Both methods are needed because different keys can have the same hash code.
What happens when two keys have the same hashCode() in Java HashMap?
When two keys have the same hashCode() or bucket index, a collision occurs in Java HashMap. HashMap handles collisions using a linked list and may convert it into a red-black tree when the bucket becomes large. It uses equals() to identify the correct key.
Learn Core Java and Collections at SevenMentor
Writing dependable Java programs requires an understanding of HashMap. The Java course offered by SevenMentor helps students create a solid foundation in Java development by covering Core Java, collections, exception handling, and multithreading.
Explore the syllabus and practical learning options to see which programme matches your current Java experience.
SevenMentor
Written by the SevenMentor training team, who teach IT and professional courses across our branches and online.