HashMap<K, V> · Java

put / putIfAbsent

Associates a value with a key, replacing any previous value (putIfAbsent only adds).

public V put(K key, V value); public V putIfAbsent(K key, V value)

Complexity

ExpectedO(1)
AmortizedO(1) including resizes
Worst caseO(n) with pathological hashing; O(log n) per tree bin in OpenJDK when keys are Comparable
Extra spaceO(1) amortized

Assumes: hashCode spreads keys over the bins (the documentation states constant time under this assumption).

Hash, pick bin hash & (n − 1), scan the bin for an equal key, link a new node. A resize doubles the table and splits each bin.

Tested example

Map<String, Integer> ages = new HashMap<>();
assert ages.put("ada", 36) == null; // returns the previous value, or null
assert ages.put("ada", 37) == 36;   // replaces
ages.putIfAbsent("ada", 99);        // no change: key present
assert ages.get("ada") == 37;
Runs in the test suite on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/test/java/dev/bekadan/dsa/collections/HashMapExamples.java

Parameters

key
Any object, or null.
value
Any object, or null.

Behaviour

Returns
The previous value, or null if there was none (or it was null).
Errors and preconditions
None.
Changes
Adds or replaces one entry; may resize (rehash every entry).
Memory and invalidation
Resize allocates a new table. Structural changes invalidate iterators.