Card 03/ 09
All 9 cards
ExampleDifficulty: Intermediate1 min
The Same Invoice Sorted Three Ways by Three Callers
The finance screen wants the largest amounts first. The chase list wants the oldest due date. The audit export wants reference order. None of those is the invoice's business.
invoices.sort(Comparator.comparingLong(Invoice::pence).reversed());
chasing.sort(Comparator.comparing(Invoice::due));
export.sort(Comparator.comparing(Invoice::reference));Three orders, three call sites, and not a line added to Invoice. A Comparator is an object that answers the same two-argument question, built where the ordering is wanted rather than where the type is declared.
Put this beside the invoice that sorts itself and the shared structure comes out: in both cases something implemented a two-argument comparison, and the only difference is who owns it. Comparable makes the answer part of the type, for everyone, permanently. Comparator makes it an argument, decided per call.