Card 08/ 09

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 four combinations to judge
The combination
1A TreeMap with a key class that implements nothing
2A HashMap with one null key
3A HashMap with a key class that overrides equals only
4A LinkedHashMap read in a loop, expecting insertion order
What each of the four does
Each combination, what happens, and why
What happensWhy
1Throws on the second putA sorted map must compare keys, and the class is not Comparable
2WorksA hash map special-cases null and stores it in the first bucket
3Compiles, and entries go missingEqual keys get different hashes, so get searches the wrong bucket
4WorksInsertion 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.