Java Comparable
Comparable Interface in Java
Last Updated : 29 Mar 2026
Comparable interface in Java is used to define the natural ordering of objects. It allows objects to be compared and sorted easily.
In this chapter, you will learn about the Comparable interface, how it works, and how to use it to sort objects.
What is Comparable Interface in Java?
Comparable is an interface in the java.lang package that is used to compare objects of a class. It provides the compareTo() method, which defines the natural ordering of objects. By implementing this interface, a class can specify how its objects should be sorted.
The compareTo() Method in Comparable
The compareTo() method is used to compare the current object with another object.
The syntax of the method is as follows:
Here,
- It returns a positive integer if the current object is greater.
- It returns a negative integer if the current object is smaller.
- It returns zero if both objects are equal.
Sorting Using Comparable Interface
The Comparable interface is used to sort:
- String objects
- Wrapper class objects
- User-defined class objects
The Collections.sort() method is used to sort elements of a List, and the elements must implement the Comparable interface.
Note: String and Wrapper classes already implement Comparable, so they can be sorted directly.
Example 1: Sorting User-Defined Objects (Ascending Order)
This example demonstrates how to sort objects based on age using the Comparable interface.
Output:
105 Jai 21 101 Vijay 23 106 Ajay 27
Example 2: Sorting User-Defined Objects (Descending Order)
This example demonstrates how to sort objects in reverse order using the Comparable interface.
Output:
106 Ajay 27 101 Vijay 23 105 Jai 21
Advantages of Comparable Interface
The Comparable interface provides a simple way to define the natural ordering of objects within a class. It requires minimal code and is widely used with collections like ArrayList, TreeSet, and TreeMap for sorting.
Limitations of Comparable Interface
Comparable allows sorting based on only one attribute at a time. If you need multiple sorting criteria (e.g., sort by name, then by age), Comparable is not suitable, and Comparator should be used instead.
Comparable vs Comparator
Comparable is used for defining the natural ordering inside the class, whereas Comparator is used to define multiple sorting orders externally without modifying the class.