← again tap: answer good → ↑ swipe up at the end: next
Question
What is a map, and what rule makes it different from a plain list of pairs?
Answer
A map stores key-value entries and is searched by key; each key appears at most once, so a key identifies exactly one entry.
A map (also called an associative array or dictionary in many languages) is a collection of entries (k, v). You do not ask it for "the third element"; you ask it for "the value stored under key k". Its main operations are therefore insert, search and delete, all addressed by key.
The defining rule is one entry per key. Storing a second value under an existing key does not add a second entry; it replaces the old value. That is what lets a map answer get(k) with a single value instead of a list.
Typical uses are small databases where one field identifies a record:
- a staff directory keyed by staff number,
- a directory of places keyed by postal code,
- a symbol table in a compiler, keyed by identifier name.
Values, unlike keys, may repeat: two employees can share a salary, two postal codes can share a town name.
Compared with a priority queue: a priority queue only ever hands out its minimum and may hold the same key several times. A map is built for searching any key, and its keys are unique like IDs. Searching a heap for an arbitrary key would take $O(n)$, because heap order only runs from each leaf up to the root and says nothing about left versus right.
Go deeper:
Associative array — the abstract data type behind maps and dictionaries, and the usual ways to implement it.
Question
What do the map operations get(k), put(k, v) and remove(k) return?
Answer
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.