Card 04/ 09

ComparisonDifficulty: Intermediate1 min

Comparable or Comparator: Whose Order Is It

Both answer the same question and the choice is not about convenience. It is about whether the order is a fact about the type or a preference of the caller.

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 that 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 would want different orders, or you do not own the class, write comparators.

The third row settles more real cases than the others. You cannot make String sort case-insensitively by editing String, and Comparator.comparing(String::toLowerCase) takes one line.