Card 04/ 09
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.
| 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 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.
← → move through sections and cards