Card 02/ 09

ExampleDifficulty: Intermediate1 min

An Invoice That Knows Its Own Order

An invoice has one obvious order — the date it falls due — and every part of the system agrees about it. That order belongs on the type.

java
record Invoice(String reference, LocalDate due, long pence)
        implements Comparable<Invoice> {

    @Override
    public int compareTo(Invoice other) {
        return due.compareTo(other.due);
    }
}
java
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 second argument uses the natural order, and a TreeSet uses it to decide where every element goes — which is why a class with no natural order cannot go in one.

compareTo did not implement a comparison. It delegated to LocalDate, which is already Comparable, and that is what most well-written compareTo methods do.