Card 08/ 09

ExerciseDifficulty: Advanced1 min

Practice: Which Map and Key Combinations Work

Four combinations: two work, one throws at once, and one compiles and loses entries.

A map's requirements on its keys depend on its class: hash maps need matching hashCode and equals, and a TreeMap needs keys it can compare. For each combination below, decide whether it works, throws, or compiles and misbehaves, all four before you open the answer.

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 ClassCastException on the first putA sorted map must compare keys, even the first with itself, and the class is not Comparable
2WorksA hash map special-cases null and stores it in the first of its buckets, the slots it sorts entries into
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 fails at once, checked in eclipse-temurin:21-jdk: a TreeMap compares even its first key with itself, so a test with a single entry already throws.

The third is the only silent one, and the most common. It is why equals and hashCode are written together or not at all.