HashMap<K, V> · Java

get

Returns the value for a key, or null if it is absent.

public V get(Object key)

Complexity

ExpectedO(1)
Worst caseO(n), or O(log n) with tree bins
Extra spaceO(1)

Assumes: Good hash distribution.

One hash and a short bin scan.

Tested example

Map<String, Integer> ages = new HashMap<>();
ages.put("ada", 36);
ages.put("ghost", null);            // HashMap allows null values (and one null key)
assert ages.get("ada") == 36;
assert ages.get("nobody") == null;  // missing...
assert ages.get("ghost") == null;   // ...or present with a null value: get cannot tell
assert ages.containsKey("ghost");
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
The key.

Behaviour

Returns
The value, or null.
Errors and preconditions
None.
Changes
Nothing.
Memory and invalidation
No allocation.