Understanding Comparable Interface

Let's discuss Comparable Interface in Java.

Comparable introduction

Collections.sort() method sorts the given List in ascending order. But the question is, how does the sort() method decide which element is smaller and which one is larger?

Each wrapper class(Integer, Double, or Long), String class, and Date class implements an interface called Comparable. This interface contains a compareTo(T o) method which is used by sorting methods to sort the Collection. This method returns a negative integer, zero, or a positive integer if this object is less than, equal to, or greater than the object passed as an argument.

If we use the Collections.sort(List<T> list) method to sort an ArrayList, then the class whose objects are stored in the ArrayList must implement the Comparable interface. If the ArrayList stores an Integer, a Long, or a String, then we don’t need to worry as these classes already implement the Comparable interface. But if the ArrayList stores a custom class object, then that class must implement the Comparable interface.

In the below example, we have a custom class called Employee. We have stored some Employee objects in an ArrayList, and we need to sort it. The below example will not compile as the Employee class does not implement the Comparable interface.

Get hands-on with 1400+ tech skills courses.