Skip to content
C

Comparable

Comparable is an interface that lets you define the "natural" sorting order for objects of your own class, by implementing its single method, compareTo().


1. What is Comparable?

Comparable is an interface that lets you define the "natural" sorting order for objects of your own class, by implementing its single method, compareTo().

2. Why is it used?

When you have a custom class (like Student) and want collections of its objects (like a List<Student> or TreeSet<Student>) to sort automatically, you implement Comparable to define exactly how two objects of that class should be compared.

3. Real-Life Example

Think of defining a general house rule: "Always arrange books by their title, alphabetically." Once this rule is set, any bookshelf using it automatically knows how to arrange the books, without needing separate instructions each time.

4. Syntax

java
class ClassName implements Comparable<ClassName> { public int compareTo(ClassName other) { // comparison logic } }

5. Example Program

java
class Student implements Comparable<Student> { String name; int marks; Student(String name, int marks) { this.name = name; this.marks = marks; } public int compareTo(Student other) { return this.marks - other.marks; } } import java.util.*; public class ComparableDemo { public static void main(String[] args) { List<Student> students = new ArrayList<>(); students.add(new Student("Riya", 85)); students.add(new Student("Aman", 70)); Collections.sort(students); for (Student s : students) { System.out.println(s.name + ": " + s.marks); } } }

Output:

Aman: 70
Riya: 85

6. Key Points to Remember

  • Comparable defines only one, single "natural" sorting order per class.
  • The compareTo() method should return a negative number, zero, or a positive number, depending on the comparison result.
  • Use Comparator (next topic) when you need multiple, different sorting orders for the same class.