HashMap is one of the most commonly used data structures in Java for storing key-value pairs. Internally, it uses an array of buckets and a hashing mechanism to provide fast insertion, retrieval, and deletion operations. It achieves near O(1) average time complexity for most operations by efficiently distributing keys across buckets.
Internal Structure of HashMap
A HashMap consists of an array called the bucket array.
Bucket[0]
Bucket[1]
Bucket[2]
Bucket[3]
...
Bucket[n]
How put() Works
map.put("Java", 100);
Step 1: Calculate Hash Code
hashCode() is called on the key.
"Java".hashCode()
Step 2: Determine Bucket Index
HashMap converts the hash value into a bucket index.
index = hash & (capacity - 1)
Step 3: Store the Entry
How get() Works
map.get("Java");
Calculate hashCode() of the key.
Find the bucket index.
Search the bucket.
Return the associated value.
Collision Handling
A collision occurs when multiple keys map to the same bucket.
Key A → Bucket 5
Key B → Bucket 5
Both keys cannot occupy the same position directly.
Collisions were handled using a Linked List.
KeyA -> KeyB -> KeyC
When the number of nodes in a bucket exceeds a threshold (8 by default), the Linked List is converted into a Red-Black Tree.
KeyB
/ \KeyA KeyC
Adding employee records into a HashMap.
import java.util.HashMap;
import java.util.Map;
public class Demo {
public static void main(String[] args) {
Map<Integer, String> employees =
new HashMap<>();
employees.put(101, "John");
employees.put(102, "David");
employees.put(103, "Mike");
System.out.println(
employees.get(102));
}
}David
Role of hashCode() and equals()
Both methods work together to ensure correct storage and retrieval.
Time Complexity
Operation Average Case
put() O(1)
get() O(1)
remove() O(1)
O(n)
or
O(log n)when treeified buckets are involved.
Important HashMap Features
HashMap vs LinkedHashMap vs TreeMap
A concise interview answer is
HashMap internally uses an array of buckets to store key-value pairs. When a key is inserted, its hashCode() determines the bucket location, and equals() is used to identify the correct key within that bucket. Collisions are handled using Linked Lists and, from Java 8 onwards, Red-Black Trees for better performance. This design enables average O(1) time complexity for insertion and retrieval operations.
Last updated: 11 November 2026
Previous question: What is the internal implementation of ArrayList and LinkedList?
Next question: What happens when two keys have the same hash code? How would you handle this scenario?