Video in progress

What is the Comparable interface for?

Comparable gives a class a "natural order": through the compareTo method an object compares itself with another one. After that, Collections.sort, TreeSet and TreeMap can sort it without an extra comparator.

📖 Answer

If compareTo returns a negative number, the current object is smaller; 0 means equal; positive means greater.

public record Course(String title, int price) implements Comparable<Course> {
    @Override
    public int compareTo(Course other) {
        return Integer.compare(price, other.price); // by price
    }
}

List<Course> list = new ArrayList<>(courses);
Collections.sort(list);   // cheapest to most expensive

String, Integer, LocalDate and BigDecimal are already Comparable.

A common mistake is return price - other.price;. With large numbers it overflows and the sign flips. It is better to use Integer.compare or Comparator.comparingInt.

If you need to sort the same class in different ways (by price and by title), use a Comparator instead.