Card 08/ 09
All 9 cards
ExerciseDifficulty: Advanced1 min
Four Maps and Four Keys: Which Combinations Work
Four map types and four things people put in them. Decide which combinations work, which throw and which compile and misbehave. All before the reveal.
| The combination | |
|---|---|
| 1 | A TreeMap with a key class that implements nothing |
| 2 | A HashMap with one null key |
| 3 | A HashMap with a key class that overrides equals only |
| 4 | A LinkedHashMap read in a loop, expecting insertion order |
What each of the four does
| What happens | Why | |
|---|---|---|
| 1 | Throws on the second put | A sorted map must compare keys, and the class is not Comparable |
| 2 | Works | A hash map special-cases null and stores it in the first bucket |
| 3 | Compiles, and entries go missing | Equal keys get different hashes, so get searches the wrong bucket |
| 4 | Works | Insertion order is exactly what this map promises |
The first throws on the second put rather than the first, which is worth noticing. One key needs no comparison, so a test with a single entry passes.
The third is the only silent one, and it is the most common. It is why equals and hashCode are written together or not at all.