Card 02/ 09
Comparable Example: An Invoice Sorted by Due Date
One order everybody agrees on belongs on the type, and then sort and TreeSet just work.
Implementing Comparable gives a class a natural order, the one order its own compareTo defines, that sorting methods and sorted collections use automatically. An invoice has one obvious order, the date it falls due, which every part of the system agrees on, so that order belongs on the type:
record Invoice(String reference, LocalDate due, long pence)
implements Comparable<Invoice> {
@Override
public int compareTo(Invoice other) {
return due.compareTo(other.due);
}
}List<Invoice> invoices = new ArrayList<>(loadInvoices());
Collections.sort(invoices);
SortedSet<Invoice> byDue = new TreeSet<>(invoices);Both lines work with no further help. sort with no comparator uses the natural order, and a TreeSet uses it to decide where each element goes, which is why a class with no natural order cannot be put in one unless the TreeSet is given a Comparator when it is created.
compareTo did not implement a comparison itself. It delegated to LocalDate, which is already Comparable, and that is what most well-written compareTo methods do.
← → move through sections and cards