Card 09/ 09
Recap: Sorting Your Own Types
The comparison question, who owns the order, chains, overflow, and consistency.
Sorting your own types comes down to the five ideas below, each listed with the card that covers it.
| The idea | Where |
|---|---|
| Every sort rests on one two-argument question: which comes first | Sorting Your Own Types: The Comparison Every Sort Relies On |
Comparable puts the order on the type; Comparator puts it at the call | Comparable vs Comparator |
thenComparing acts on ties; reversed() reverses everything to its left | Building a Comparator on Two Fields With One Reversed |
Subtracting two int values can overflow and flip the sign | Integer Overflow in Comparators: Why Subtraction Is a Bug |
| An inconsistent comparator throws on some lists and misorders others | Comparator Contract Violations: "Comparison Method Violates Its General Contract" |
Build comparators from comparing and thenComparing rather than arithmetic; both failures here disappear.
← → move through sections and cards