Sub topic 6
Comparator consistency and what makes two keys equal
This chapter assumes you know how maps and sets work, can read Big-O notation, and have seen a comparator (a function that orders two values). It covers one idea: in an ordered collection, the comparator decides which keys are the same.
Equality comes from the comparator
A hash map decides that two keys are the same by calling equals and hashCode. A sorted map or sorted set never calls them. It treats two keys as equal when the comparator returns 0.
import java.util.TreeSet;
TreeSet<String> names = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
names.add("Apple");
names.add("apple");
System.out.println(names.size()); // 1"Apple".equals("apple") is false. The comparator returns 0, so the second add is treated as a duplicate and the set keeps only "Apple". For a map, a second put with such a key replaces the value but keeps the original key object.
What consistent means
A comparator must behave like a real ordering. For all keys a, b and c:
- Antisymmetry: the sign of
compare(a, b)is the opposite of the sign ofcompare(b, a). - Transitivity: if
a < bandb < c, thena < c. - Equal keys compare alike: if
compare(a, b) == 0, thencompare(a, c)andcompare(b, c)have the same sign.
If a rule fails, the tree or binary search can take a wrong branch. Lookups then miss keys that are present, and inserts can place keys where later searches never look.
Consistent with equals
A comparator is consistent with equals when compare(a, b) == 0 exactly when a.equals(b). The case-insensitive set above is not consistent with equals. That is legal, but the collection no longer follows the general Set contract, which is defined in terms of equals. Code that moves the same keys between a HashSet and a TreeSet can then give different answers.
A common bug: comparing only part of the key
A frequent mistake is sorting records by one field. Suppose you store players ordered by score:
import java.util.Comparator;
import java.util.TreeSet;
record Player(String name, int score) {}
TreeSet<Player> board = new TreeSet<>(Comparator.comparingInt(Player::score));
board.add(new Player("Ana", 90));
board.add(new Player("Ben", 90));
System.out.println(board.size()); // 1, Ben was droppedTwo different players with the same score compare as 0, so Ben is silently dropped. The fix is a tie-breaker that makes the order total over the data you store:
Comparator<Player> byScoreThenName =
Comparator.comparingInt(Player::score).thenComparing(Player::name);Other traps
- Subtraction overflow.
return a - b;breaks for large or negative values. UseInteger.compare(a, b). - Floating-point NaN.
NaNis not ordered by<, so useDouble.compare. - Changing the order later. Mutating a field the comparator reads, after insertion, breaks the structure. The pitfalls chapter returns to this.
Exercise
A TreeMap<String, Integer> is built with String.CASEINSENSITIVEORDER. You call put("Key", 1) and then put("KEY", 2). What does the map contain, and which key object does it hold?
Show answer
One entry. The comparator returns 0 for the two strings, so the second put replaces the value. The map holds the original key "Key" with the value 2.
Exercise
Why does a comparator that returns a - b for ints fail, and what should replace it?
Show answer
The subtraction can overflow, for example Integer.MAX_VALUE - (-1), which flips the sign and breaks the ordering. Use Integer.compare(a, b).