Course contentsShow
← Java
Lesson 1315 of 2,87030. Comparable and ComparatorFree lesson

Sorting with Collections.sort and Arrays.sort

Once a class implements Comparable, you can sort lists with Collections.sort and arrays with Arrays.sort automatically.

Sorting with Collections.sort and Arrays.sort

What You'll Learn

You'll discover how implementing Comparable lets you sort collections and arrays automatically using Java's built-in sorting methods.

The Power of Comparable

Once your class implements Comparable<T> and defines compareTo(), Java's standard library can sort your objects without any extra work. Think of it like adding a "sort key" to your objects—once that's in place, Java knows how to arrange them in order.

Two primary methods unlock this capability:

  • Collections.sort(List<T> list) — sorts lists
  • Arrays.sort(T[] array) — sorts arrays

Both rely on your class's natural ordering (the compareTo method you defined).

How It Works in Practice

When you call Collections.sort() on a List of Comparable objects, Java examines pairs of elements using their compareTo method and rearranges them accordingly. The same principle applies to Arrays.sort() for arrays.

class Student implements Comparable<Student> {
    String name;
    int age;
    
    public int compareTo(Student other) {
        return Integer.compare(this.age, other.age);
    }
}

List<Student> students = new ArrayList<>();
students.add(new Student("Alice", 22));
students.add(new Student("Bob", 19));
students.add(new Student("Carol", 21));

Collections.sort(students); // Sorts by age automatically

For arrays:

Student[] studentArray = {
    new Student("Alice", 22),
    new Student("Bob", 19)
};

Arrays.sort(studentArray); // Also sorts by age

No custom sorting logic needed—compareTo handles everything!

Why This Matters

This design follows the Dependency Inversion Principle: the sorting algorithms depend on the Comparable abstraction, not on specific class details. You define the ordering once in compareTo, and every sorting utility respects it.

Key Takeaway: Implementing Comparable enables automatic sorting with Collections.sort() for lists and Arrays.sort() for arrays, leveraging your class's natural ordering defined in compareTo().