Card 01/ 09
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:
int compare(Invoice a, Invoice b)| Returns | Means |
|---|---|
| A negative number | a comes before b |
| Zero | Neither comes first: they tie |
| A positive number | a 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