Card 01/ 09

ConceptDifficulty: Intermediate1 min

Teaching Java the Order Your Type Already Has

Sorting a list of numbers is one line. Sorting a list of invoices is a compile error, because nothing in the library knows whether an invoice comes before another by date, by amount or by reference.

Every sort in Java is built on the same tiny question, asked over and over: given these two, which comes first? Your job is to answer it once.

java
int compare(Invoice a, Invoice b)
What the answer to that question means
ReturnsMeans
A negative numbera comes before b
ZeroNeither comes first — they tie
A positive numbera comes after b

There are two places to put that method. Comparable puts it on the class, as compareTo, and makes it the type's one natural order. Comparator puts it in a separate object the caller supplies, which lets one type be sorted many ways.

So sorting your own types is never about the sorting algorithm. It is about deciding who owns the order — the type, or whoever is asking.