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

The Comparable<T> Interface

Comparable is a generic interface with one method, compareTo, that defines how objects of a class compare to each other.

The Comparable<T> Interface

What you'll learn: How the Comparable<T> interface allows objects to define their own natural ordering through the compareTo method.


What Is Comparable?

Comparable<T> is a generic interface that enables objects to be compared with each other. When a class implements Comparable<T>, it defines its natural ordering — the default way instances of that class should be sorted.

The interface has a single method:

public interface Comparable<T> {
    int compareTo(T other);
}

How compareTo Works

The compareTo method compares the current object (this) with another object (other) and returns:

  • Negative integer if this is less than other
  • Zero if this is equal to other
  • Positive integer if this is greater than other

Think of it like asking: "Where do I belong relative to you?" The answer is a number indicating whether you come before, at the same position, or after.

A Simple Example

public class Student implements Comparable<Student> {
    private String name;
    private int age;

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public int compareTo(Student other) {
        // Natural ordering by age
        return this.age - other.age;
    }
}

Now Student objects can be sorted by age automatically using methods like Collections.sort(), because the class defines how students should be ordered.

Why It Matters

Implementing Comparable<T> unlocks sorting and searching capabilities. Without it, Java wouldn't know how to order your custom objects.

Key Takeaway: Comparable<T> defines natural ordering for a class by implementing the compareTo method, which returns negative, zero, or positive values to indicate relative ordering.