11.11. Comparable Interface

Comparable Interface

  • Eclipse: Oxygen
  • Java: 1.8

Comparable Interface

The comparable class is shown here. The syntax of the comparable class is unique to the others which include objects and the class. This class can be used for various purposes as shown in the tutorial. The Comparable interface is found in java.lang package. It contains only one method named compareTo(Object).

A comparable Interface is used to sort the custom-type objects. By default, a class defined by the user is not comparable. Hence, their objects cannot be compared. To make an object comparable, the class must implement a comparable interface.

A comparable interface can be used to achieve a single way of sorting like ascending or descending sorting the numerical collection or alphabetical sorting for string object collection.

In the following program, class data implements a Comparable interface. Implement the unimplemented compareTo() method based on the length of the String variable. This method accepts an object of the same instance type and based on certain criteria defined, it returns a negative value if the current value is less than the value we are comparing with, respectively.

Output

Let’s see the same example of the Comparable interface that sorts the list elements on the basis of name length in reverse order(modify the implementation of compareTo() method).

Output

Contributed by: Poonam Tomar

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments