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
| Expected | O(1) |
|---|---|
| Amortized | O(1) including resizes |
| Worst case | O(n) with pathological hashing; O(log n) per tree bin in OpenJDK when keys are Comparable |
| Extra space | O(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;
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.