Card 04/ 09
All 9 cards
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.
| Compared on | Comparable | Comparator |
|---|---|---|
| Lives | On the class, as compareTo | In a separate object, at the call site |
| How many per type | One | As many as you like |
| Needs the class's source | Yes | No — works on types you do not own |
| Used by default | sort with no argument, TreeSet, TreeMap | Only when passed in |
Should agree with equals | Yes, strongly | Not 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.