0Pricing
Java Academy · Lesson

The Comparable Interface

Implement Comparable to give a class a natural ordering and use it with Collections.sort.

The Comparable Interface

Comparable<T> gives a class a natural ordering. Implement it to make instances sortable with Collections.sort(), Arrays.sort(), and sorted collections like TreeSet.

Implementing Comparable

Implement compareTo(T other) returning negative (this < other), zero (equal), or positive (this > other).

class Product implements Comparable<Product> {
    private final String name;
    private final double price;

    Product(String name, double price) {
        this.name = name; this.price = price;
    }

    @Override
    public int compareTo(Product other) {
        return Double.compare(this.price, other.price); // ascending by price
    }

    @Override public String toString() { return name + "($" + price + ")"; }
}

List<Product> products = new ArrayList<>(List.of(
    new Product("Mouse", 29.99),
    new Product("Laptop", 999.0),
    new Product("Keyboard", 79.99)
));
Collections.sort(products);
System.out.println(products); // [Mouse($29.99), Keyboard($79.99), Laptop($999.0)]

All lessons in this course

  1. The Comparable Interface
  2. Comparator and Lambda Sorting
  3. Multi-Key Sorting with thenComparing
  4. Sorting Arrays and Collections in Practice
← Back to Java Academy