Java Comparable Interface


The java.lang package includes the Comparable interface. The Comparable interface allows developers to specify the natural order of Java objects. When a class implements Comparable it enables its objects to be arranged in order through sorting methods such as Collections.sort() or Arrays.sort().


Key Features

  • Enables default sorting logic
  • Requires implementation of compareTo() method
  • The Comparable interface supports sorting using Collections.sort() and Arrays.sort().
  • Belongs to java.lang (no need to import)

Interface Declaration

public interface Comparable {
    public int compareTo(T o);
} 

Method Signature

int compareTo(T other);

Return values:

  • 0 – current object is equal to other
  • < 0 – current object is less than other
  • > 0 – current object is greater than other

Example

import java.util.*;

public class ComparableExample {
    public static void main(String[] args) {
        List list = new ArrayList<>();
        list.add(new Student(102, "Alice"));
        list.add(new Student(101, "Bob"));
        list.add(new Student(103, "Charlie"));

        Collections.sort(list);  // uses compareTo()

        for (Student s : list) {
            System.out.println(s.id + " - " + s.name);
        }
    }
}

Note

  • Comparable functionality requires you to override the compareTo() method.
  • Use Comparator when:
  • You need multiple sort orders.
  • Modifying the class is not an option such as in third-party classes.

Comparable vs Comparator

Feature Comparable Comparator
Defined in class Yes (compareTo()) No (separate class, compare())
Sorting logic Natural/default Custom/multiple
Used by Collections.sort(), Arrays.sort() Collections.sort(list, comparator)



Onlinetpoint is optimized for basic learning, practice and more. Examples are well checked and working examples available on this website but we can't give assurity for 100% correctness of all the content. This site under copyright content belongs to Onlinetpoint. You agree to have read and accepted our terms of use, cookie and privacy policy.