Comparable Interface

  • Eclipse: Oxygen
  • Java: 1.8

Comparable Interface

The comparable class is shown here. The syntax of the comparable class which is unique than the others which include objects and the class. This class can be used for various purposes as shown in the tutorial.

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.

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 Comparable interface. Implement the unimplemented compareTo() method based on the length of the String variable. This method accepts an object of 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

Element: Chaand

Element: Ed

Element: John

Element: Mia

******************

Element: Ed

Element: Mia

Element: John

Element: Chaand

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

Element: Chaand

Element: Ed

Element: John

Element: Mia

******************

Element: Chaand

Element: John

Element: Mia

Element: Ed

Contributed by: Poonam Tomar


Full stack Java Developer

   Buy me a coffee!

 

PayTM QR (INDIA)

Download file

Leave a Reply

avatar
  Subscribe  
Notify of
Close Menu