DEV Community

Cover image for Comparable Interface in Java
Vidya
Vidya

Posted on

Comparable Interface in Java

Comparable Interface

The Comparable Interface in Java is used to define the natural ordering of objects within a class. It is available in the java.lang package and contains only one method called compareTo(). By implementing this interface, a class can specify how its objects should be compared and sorted. It is commonly used with sorting methods like Collections.sort() or Arrays.sort().

Example:

 import java.util.*;

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

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

    public int compareTo(Student s) {
        return this.age - s.age; // sorting by age
    }
}

public class Main {
    public static void main(String[] args) {
        ArrayList<Student> list = new ArrayList<>();
        list.add(new Student(22, "A"));
        list.add(new Student(18, "B"));
        list.add(new Student(20, "C"));

        Collections.sort(list);

        for (Student s : list) {
            System.out.println(s.age + " " + s.name);
        }
    }
}            --> output: 18 B  
                         20 C  
                         22 A  
Enter fullscreen mode Exit fullscreen mode

Real-Time theoretical examples of the Comparable Interface

1. Bank Transactions Sorting

In banking apps, transactions are sorted by date or amount. Using Comparable, transactions can have a natural order like latest first.

2. Flight Ticket Booking Systems

Airlines sort flights by departure time or ticket price so users can easily choose the best option.

3. Hospital Patient Priority

Hospitals may sort patients based on severity level or emergency priority to decide treatment order.

Why we use Comparable?

We use the Comparable Interface in Java to define a natural sorting order for objects of a class. It allows objects to be compared with each other using the compareTo() method, so they can be easily sorted. This is useful when working with collections like lists, where we want automatic ordering without writing extra logic every time. Overall, it helps make sorting simple, consistent, and built directly into the class itself.

Top comments (0)