Card 08/ 09
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 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 ClassCastException on the first put | A sorted map must compare keys, even the first with itself, and the class is not Comparable |
| 2 | Works | A hash map special-cases null and stores it in the first of its buckets, the slots it sorts entries into |
| 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 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.
← → move through sections and cards