The employee who disappeared from the set
A medium Java puzzle in the collections contracts family. One line below contains a real bug. Try to spot it first, then read why it fails and how to fix it.
Highlighted: line 7. Play this one as a puzzle without the answer.
What is wrong
TreeSet decides whether two elements are duplicates with the comparator, not with equals. Ann and Bob compare as 0, so Bob is treated as already present and is dropped. The set has two elements instead of three.
The fix
How to avoid it next time
Make a comparator consistent with equals by adding tie-breakers, or use a list for non-unique ordering.
Want the background? Read TreeMap, TreeSet and sorted collections in the Java concepts library.
About collections contracts
Collection classes come with contracts about ordering, mutability and key behavior. Fixed-size lists, views of other collections and mutable map keys break those contracts without compile errors.
In code review: Check what the factory method returns, whether the result is modified later, and whether objects used as keys can change after insertion.
More puzzles in this family
Frequently asked questions
What is the bug in "The employee who disappeared from the set"?
TreeSet decides whether two elements are duplicates with the comparator, not with equals. Ann and Bob compare as 0, so Bob is treated as already present and is dropped. The set has two elements instead of three. The faulty line is line 7: Set
How do I fix it?
Replace it with: new TreeSet<>(Comparator.comparingInt(Person::age).thenComparing(Person::name)). Make a comparator consistent with equals by adding tie-breakers, or use a list for non-unique ordering.
How do I catch collections contracts in code review?
Check what the factory method returns, whether the result is modified later, and whether objects used as keys can change after insertion.
Is there a new puzzle every day?
Yes. The daily Spot the Bug puzzle picks one of these snippets for each UTC day, with the difficulty set by the weekday. Your streak is stored only in your browser.