Java Comparable interface is used to define object’s natural ordering. The Comparable interface has only one method named compareTo.

The comparable interface is contained in the java.lang package which is imported by default in the code. You do not need to import any packages using import statement to use Comparable interface in your code.

int compareTo(T object)

The compareTo method returns a negative number if this object is less than the specified object, zero if they are equal and positive number if this object is greater than the specified object.

Please note that the compareTo method throws NullPointerException if the specified object is null and ClassCastException if the specified object type is a mismatch.

In order to define the natural ordering of the objects of the class, the class must implement Comparable interface and define the compareTo method. Once the compareTo method is defined, it will be referred automatically when the objects of the class is being sorted using sort method of Collections class or Arrays class.

The Comparator interface is useful when you want to sort the objects of a custom class by attributes of it. For example, if your code has Employee class and you want to sort the employee objects by its salary.

Here are some of the Java Comparable examples which describes how to use the Java Comparable interface to sort the objects.

Java Comparable Examples

Join 1000+ fellow learners! Enter your email address below: