HashMap in Java
Learn how Java HashMap handles keys, collisions, resizing, and iteration, with expected performance, concurrency limits, and JDK-specific internals.
Learn how Java HashMap handles keys, collisions, resizing, and iteration, with expected performance, concurrency limits, and JDK-specific internals.
HashMap in Java
HashMap maps keys to values. It uses each key’s hashCode() to select a bucket and equals() to distinguish keys that land there. The API’s constant-time expectation for get() and put() assumes hashes distribute keys properly; collisions add comparison work.
Introduction
HashMap suits key-based access. Keep fields used by a key’s hashCode() and equals() stable while the key is in the map; changing them can make the entry unreachable until the values are restored. The map is unsynchronized. If multiple threads access it and any thread structurally modifies it, synchronize access externally or use a concurrent map. Growth also rebuilds the table, so a resize can add latency during insertion.
This post covers bucket lookup, collisions, resizing, key stability, and what fail-fast iteration does and does not guarantee.
When to Use HashMap
Use HashMap when:
- You need to store and retrieve values by a unique key
- Expected constant-time lookup is useful, and keys have a well-distributed
hashCode() - Keys are not ordered (if ordering matters, use
TreeMaporLinkedHashMap) - You need a mutable map; for immutable snapshots, consider
Map.of()orCollections.unmodifiableMap()
Do not use HashMap when:
- You need sorted or insertion-order iteration (use
TreeMaporLinkedHashMap) - You need thread-safe operations (use
ConcurrentHashMap) - You need
nullkeys in a concurrent map (ConcurrentHashMapdoes not allow them) - You need primitive-key maps without boxing (use Trove or other specialized libraries)
Internal Structure
The Java SE API specifies HashMap behavior, not a particular bucket layout. In OpenJDK 27u, a table contains Node<K,V> buckets; nodes in a bucket form a list until an implementation-specific treeification condition is met. These thresholds are OpenJDK 27u details, not API guarantees:
// OpenJDK 27u implementation details
static final int TREEIFY_THRESHOLD = 8;
static final int UNTREEIFY_THRESHOLD = 6;
static final int MIN_TREEIFY_CAPACITY = 64;
OpenJDK 27u attempts to treeify a long bucket at the threshold when the table capacity is at least 64. If the table is smaller, it resizes instead. During a resize, a tree bin that splits into a small bin may be converted back to a list at the untreeification threshold.
Mermaid Diagram: HashMap Structure
graph TD
A["HashMap<K,V>"] --> B["table: Node[16]"]
B --> C["bucket[0] → Node<K,V> → null"]
B --> D["bucket[1] → Node → Node → null"]
B --> E["bucket[2] null"]
B --> F["bucket[3] → tree bin when eligible"]
D --> D1["hash: 17<br/>key<br/>value<br/>next: Node"]
D1 --> D2["hash: 17<br/>key<br/>value<br/>next: null"]
F --> F1["TreeNode<br/>Red-Black tree"]
Hash Collisions
When different keys have the same hash code or map to the same bucket, a collision occurs. The map compares keys within that bucket. A cluster of collisions increases comparison work. OpenJDK 27u can replace long bins with tree bins under the version-specific conditions above; this behavior is not part of the HashMap API contract.
// Simplified collision handling
if (node.next == null) {
node.next = new Node(hash, key, value, null);
} else {
// OpenJDK 27u may resize or treeify a long bin, depending on capacity
}
Failure Scenarios
| Scenario | Cause | Result |
|---|---|---|
ConcurrentModificationException |
A fail-fast iterator detects an external structural change | Best-effort diagnostic; not guaranteed or a correctness tool |
| Performance degradation | Many collisions or poorly distributed hash codes | More key comparisons and slower operations |
OutOfMemoryError |
Unbounded growth | The application runs out of available memory |
Trade-Off Table
| Aspect | HashMap | TreeMap | LinkedHashMap |
|---|---|---|---|
| Ordering | None | Sorted by key (Red-Black) | Insertion or access order |
| Get/Put complexity | Expected constant time with good hash distribution | O(log n) | Expected constant time with good hash distribution |
null key allowed |
Yes (one) | No | Yes (one) |
| Thread safety | None | None | None |
| Memory overhead | Lower | Higher (tree structure) | Higher (linked list) |
Code Snippets
Basic Operations
HashMap’s everyday API boils down to four operations: put(), get(), remove(), and containsKey(). put() inserts or overwrites a value and returns whatever was previously mapped to that key — useful when you need to know whether you just clobbered something. get() retrieves by key, remove() deletes, and containsKey() checks existence.
getOrDefault() returns the default when the key is absent; get() returns null both for an absent key and a key mapped to null. Use containsKey() when that distinction matters. getOrDefault() is also useful for counting and accumulator patterns.
import java.util.HashMap;
import java.util.Map;
public class HashMapBasicsDemo {
public static void main(String[] args) {
Map<String, Integer> ages = new HashMap<>();
ages.put("Alice", 30);
ages.put("Bob", 25);
System.out.println(ages.get("Alice")); // 30
System.out.println(ages.getOrDefault("Eve", 0)); // 0
ages.remove("Bob");
System.out.println(ages.containsKey("Bob")); // false
System.out.println(ages.size()); // 1
}
}
Save this as HashMapBasicsDemo.java, then run javac HashMapBasicsDemo.java && java HashMapBasicsDemo:
30
0
false
1
Custom Key with Proper HashCode
If you use a custom object as a HashMap key, you must override both hashCode() and equals(), and both must depend on the same fields. The rule: objects that are equals() must have the same hashCode(). The reverse is not required, but violating the forward direction is the most common cause of “where did my entry go?” bugs.
Fields used by hashCode() and equals() must stay stable while a key is stored in the map. If they change, lookups may miss the entry until those fields are restored. Objects.hash() on stable fields is a common way to implement hashCode() without writing the arithmetic by hand.
A minimal correct implementation looks like this:
class Employee {
private final int id;
private final String name;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Employee that = (Employee) o;
return id == that.id;
}
@Override
public int hashCode() {
return Objects.hash(id); // Use only immutable field(s)
}
}
Iterating
HashMap gives you three iteration views. Use entrySet() when you need both the key and value — it avoids a separate hash lookup for each key. Use keySet() when you only need the keys, though for bulk access entrySet() is faster. Use values() when you only need the values.
Avoid structurally modifying the map outside its iterator while traversing a collection view. A fail-fast iterator may throw ConcurrentModificationException after such a change, but detection is best-effort and must not be used for correctness. If removal is needed, use the iterator’s supported remove() method. The HashMap API also documents that iterating a view takes time proportional to table capacity plus map size.
for (Map.Entry<String, Integer> entry : ages.entrySet()) {
System.out.println(entry.getKey() + " -> " + entry.getValue());
}
// KeySet iteration
for (String key : ages.keySet()) { }
// Value iteration
for (Integer val : ages.values()) { }
Observability Checklist
- Test representative key sets for collision-heavy
hashCode()distributions - Profile lookup and insertion costs under expected and collision-heavy workloads
- Log
size()over time to detect unbounded map growth - Review any
ConcurrentModificationExceptionas a bug signal, not a correctness mechanism - Treat treeification thresholds as implementation details; the OpenJDK 27u values are documented above
Security Notes
HashMapis unsynchronized. If multiple threads access it and any thread structurally modifies it, synchronize externally or useConcurrentHashMap.- A
Collections.synchronizedMap()wrapper requires callers to synchronize on the wrapper while iterating its views. - When using user-supplied keys, a malicious
hashCode()implementation could trigger DoS attacks (hash flooding) - Avoid serializing maps containing sensitive data; use encrypted serialization or secure alternatives
Map.of()creates an unmodifiable map;Collections.unmodifiableMap()creates an unmodifiable view of its backing map
Common Pitfalls / Anti-Patterns
- Mutable keys: If a key’s
hashCode()changes after insertion, the entry becomes unretrievable — the map cannot find it - Poor
hashCode(): Returning a constant (e.g.,return 42) places many keys in the same bucket and increases comparison work, slowing lookups and updates - Confusing
put()return value:put()returns the previous value ornull; usecontainsKey()if you need to distinguish no mapping from a previousnullvalue nullkey: Only onenullkey is allowed; subsequentput(null, value)overwrites the first- Ignoring rehashing: Growth rebuilds the table and revisits entries, which can cause an insertion latency spike. Estimate the expected size when constructing a large map.
Quick Recap
HashMapdocuments expected constant-timeget()andput()when hashes distribute keys properly- Collisions add comparison work; tree bins and thresholds are implementation details
- Keys must have stable
hashCode()and correctequals()implementations nullkey andnullvalues are supported (singlenullkey)- Unsynchronized; synchronize structural writes externally or choose
ConcurrentHashMapfor concurrent access
Interview Questions
Further Reading
- Java SE 27
HashMapAPI — expected operation costs, synchronization, and fail-fast iterator contract - OpenJDK 27u
HashMapsource — version-specific bucket and treeification implementation - Baeldung: HashMap Internals — Deep dive into hash function, collisions, and treeification
- How HashMap Works in Java — Step-by-step explanation of put/get operations and bucket handling
- Java HashMap: Performance Optimization — Capacity, load factor, and sizing strategies
- HashSet — HashMap’s set counterpart for unique element storage
- TreeMap and TreeSet — sorted key-value pairs using Red-Black trees
- ArrayList — comparing list implementations for different use cases
Conclusion
HashMap is a key-value store with expected constant-time get() and put() when hashes distribute keys properly. Collisions add comparisons, so key distribution affects observed performance. Keys also need stable hashCode() and consistent equals() behavior while stored.
Immutable keys such as String and Integer avoid key-stability problems. With custom keys, keep fields used by hashCode() and equals() unchanged while the key is stored. HashMap is unordered; use TreeMap for sorted keys or LinkedHashMap when iteration order matters.
HashSet is the set counterpart to HashMap; it uses a map internally to store unique elements. See HashSet in Java for its membership and equality behavior.
Category
Related Posts
Abstract Classes in Java: Interfaces and Composition
Compare Java interfaces, abstract classes, and composition, then see when shared state, default methods, or sealed types change the design choice.
Arithmetic Operators in Java: Division, Overflow, Promotion
Compare Java arithmetic with runnable examples of division, negative remainders, overflow, type promotion, and BigDecimal for decimal money.
Java Array Basics: Length, Bounds, Copies, and Resizing
Learn Java arrays through runtime-sized allocation, bounds checks, aliasing, copying, and the fixed length that distinguishes them from ArrayList.