Card 09/ 09

RecapDifficulty: Advanced1 min

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.

What the topic established, and which card it was on
The ideaWhere
Every sort rests on one two-argument question: which comes firstSorting Your Own Types: The Comparison Every Sort Relies On
Comparable puts the order on the type; Comparator puts it at the callComparable vs Comparator
thenComparing acts on ties; reversed() reverses everything to its leftBuilding a Comparator on Two Fields With One Reversed
Subtracting two int values can overflow and flip the signInteger Overflow in Comparators: Why Subtraction Is a Bug
An inconsistent comparator throws on some lists and misorders othersComparator Contract Violations: "Comparison Method Violates Its General Contract"

Build comparators from comparing and thenComparing rather than arithmetic; both failures here disappear.