Natural order with Comparable
Records arrived in Java 16; the Comparable part works the same on any class since Java 1.2.
Comparable gives a class one built-in natural order (compareTo), and a Comparator is a separate object that describes any other order. Sorting, TreeMap, TreeSet, PriorityQueue, min and max all work through one of the two.
Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Sort a list of words by length, shortest first, and alphabetically among words of the same length.
Write a Version record (major, minor, patch) that implements Comparable so 1.10.0 sorts after 1.9.3.
Given a Map<String, Integer> of word counts, print the entries sorted by count descending, then by word.
Explain it without notes
When would you implement Comparable, and when would you write a Comparator instead?
Why is (a, b) -> a - b a dangerous comparator, and what should you use?
Explain what "consistent with equals" means and what goes wrong in a TreeSet when it isn't.
Why does it matter that Java's object sort is stable? Give a concrete example.
Expected output
[Student[name=Ben, marks=67], Student[name=Asha, marks=82], Student[name=Cara, marks=91]]
lowest: Ben
Ben vs Cara: -1