Java · Hash map · container
HashMap<K, V>
Java's hash table map: constant-time get and put on average, one null key allowed, no ordering.
import java.util.HashMap; public class HashMap<K, V> extends AbstractMap<K, V> implements Map<K, V>, Cloneable, Serializable
Java SE 25 (tree bins since Java 8)
Operations
| Operation | Time | Worst case | Changes the collection |
|---|---|---|---|
| put / putIfAbsent | O(1) including resizes | O(n) with pathological hashing; O(log n) per tree bin in OpenJDK when keys are Comparable | Yes |
| get | O(1) | O(n), or O(log n) with tree bins | No |
| getOrDefault / merge | O(1) | O(n) | Yes |
| containsKey / containsValue | O(1) for containsKey | O(n) for containsValue (always) | No |
| remove | O(1) | O(n), or O(log n) with tree bins | Yes |
"Time" shows the amortized, expected or average bound when one applies; open an operation for the full profile and its assumptions.
How it works
- Representation
- An array of bins (power-of-two length) with separate chaining. In OpenJDK, a bin that grows past 8 entries in a table of at least 64 bins becomes a red-black tree (ordered by hash and, when possible, Comparable keys).
- Ordering
- None, and it can change after a resize. LinkedHashMap keeps insertion (or access) order; TreeMap keeps keys sorted.
- Duplicates
- Keys are unique; values may repeat.
- Mutability
- Mutable; fail-fast iterators.
- Memory and ownership
- Default load factor 0.75: the table doubles when size exceeds 0.75 × capacity. A Node object per entry.
- Equality and comparison
- Keys use hashCode() then equals(); both must be consistent and must not change while the key is in the map.
Pitfalls
- get returns null both for a missing key and for a key mapped to null; use containsKey or getOrDefault.
- Overriding equals without hashCode makes equal keys land in different bins.
- Iteration order is not insertion order; use LinkedHashMap if that matters.
Alternatives
- LinkedHashMap (predictable order, LRU caches)
- TreeMap (sorted keys, O(log n))
- EnumMap for enum keys
- ConcurrentHashMap between threads
In other languages
- C#: Dictionary<TKey, TValue>
- Python: dict
- C++: std::unordered_map<Key, T>