HashMap<K, V> · Java
remove
Removes a key (optionally only if mapped to a given value).
public V remove(Object key); public boolean remove(Object key, Object value)
Complexity
| Expected | O(1) |
|---|---|
| Worst case | O(n), or O(log n) with tree bins |
| Extra space | O(1) |
Find the node in its bin and unlink it. The table does not shrink.
Tested example
Map<String, Integer> ages = new HashMap<>(Map.of("ada", 36, "bob", 25));
assert ages.remove("bob") == 25;
assert ages.remove("bob") == null; // missing: null, no exception
assert ages.remove("ada", 99) == false; // remove(key, value) only if it matches
assert ages.size() == 1;
Parameters
- key
- The key.
Behaviour
- Returns
- The removed value or null; the two-argument form returns whether it removed.
- Errors and preconditions
- None.
- Changes
- Unlinks one node.
- Memory and invalidation
- Does not shrink.