Card 01/ 09

ConceptDifficulty: Intermediate1 min

Sorting Your Own Types: The Comparison Every Sort Relies On

Given two invoices, which comes first? Answer that once, and every sort in Java can use it.

Every sort in Java is built on one question, asked over and over: given these two elements, which comes first? For numbers and strings the library already knows the answer. For your own classes you supply it, either on the class with Comparable or separately with a Comparator.

Sorting a list of numbers is one line. Sorting a list of invoices does not compile, because nothing in the library knows whether one invoice comes before another by date, by amount or by reference. The compiler refuses Collections.sort(invoices) outright, because Invoice does not say how to compare two invoices. The answer is a method of this shape:

java
int compare(Invoice a, Invoice b)
What the result of a comparison 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 itself, 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. Both answers use the same three possible results, so learning to write one comparison teaches you both.

← → move through sections and cards