What do the map operations get(k), put(k, v) and remove(k) return?
get returns the value for k or null; put returns the old value it replaced, or null if k was new; remove returns the value it removed, or null if k was absent.
| Operation | Key k present | Key k absent |
|---|---|---|
get(k) |
its value | null |
put(k, v) |
replaces the value with v, returns the old value | adds (k, v), returns null |
remove(k) |
deletes the entry, returns its value | null |
So put does double duty: insert and update. Its return value works like a receipt, telling the caller which of the two happened without a separate lookup. A first put(3000, Bern) returning null is therefore a success, not an error; a second put(3000, …) hands back "Bern".
The three views of a map return collections:
keySet(): all keys. A set, because keys are unique.values(): all values. A plain collection, because values may repeat.entrySet(): all(k, v)pairs. Also a set: since no two entries share a key, no two entries can be equal.- plus
size()andisEmpty().
Gotcha: null as "not found" is ambiguous when a map may store null as a value. Java's HashMap allows that, so get(k) == null cannot tell "absent" from "stored null"; use containsKey(k) when it matters.
Go deeper:
Java Map interface — the real
get,putandremovecontracts, including what they return.