Card 09/ 09
All 9 cards
RecapDifficulty: Advanced1 min
One Natural Order, Many Requested Ones
Five things this topic established, and where each one was.
| The thing | Where |
|---|---|
| Every sort rests on one two-argument question: which of these comes first | Teaching Java the Order Your Type Already Has |
Comparable puts the order on the type; Comparator puts it at the call | Comparable or Comparator: Whose Order Is It |
thenComparing only runs on a tie, and reversed() reverses everything to its left | Building a Comparator That Sorts on Two Fields |
Subtracting two int values can overflow and flip the sign | Why Subtracting Two ints in a Comparator Is a Bug |
| An inconsistent comparator throws on some lists and silently misorders others | Why Your Sort Threw |
The one worth carrying: build comparators out of comparing and thenComparing rather than writing the arithmetic. Both failures in this topic come from hand-written comparison logic, and both disappear when the combinators write it for you.