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

OperationTimeWorst caseChanges the collection
put / putIfAbsentO(1) including resizesO(n) with pathological hashing; O(log n) per tree bin in OpenJDK when keys are ComparableYes
getO(1)O(n), or O(log n) with tree binsNo
getOrDefault / mergeO(1)O(n)Yes
containsKey / containsValueO(1) for containsKeyO(n) for containsValue (always)No
removeO(1)O(n), or O(log n) with tree binsYes

"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

References