Card 04/ 09

ComparisonDifficulty: Intermediate1 min

Comparable vs Comparator

The order is either a fact about the type or a preference of the caller.

Comparable and Comparator answer the same question, which of two elements comes first, and the choice between them is not about convenience. It is whether the order is a fact about the type or a preference of whoever is sorting.

The two ways to supply an order, on where it lives and what it costs
Compared onComparableComparator
LivesOn the class, as compareToIn a separate object, at the call site
How many per typeOneAs many as you like
Needs the class's sourceYesNo: works on types you do not own
Used by defaultsort with no argument, TreeSet, TreeMapOnly when passed in
Should agree with equalsYes, stronglyNot required

The decision rule. If there is one order everybody would agree is the order (a date for an event, a number for a score, alphabetical for a name), put it on the type. If reasonable people want different orders, or you do not own the class, write separate comparators for each caller instead.

The third row settles most real cases. You cannot make String sort without regard to case by editing String, and Comparator.comparing(String::toLowerCase) does it in one line.