interface Comparable

In Java, we come across a list of objects like all employees or all students etc. Many a times, it is required to sort them for customization. For example, a student may be required to sort by his roll number, name or marks etc.

To sort the objects, Java comes with two interfaces – java.lang.Comprable and java.util.Comparator. A class that requires sorting using these interfaces, should implement these interfaces and override their abstract method. Now let us see interface Comparable and later interface Comparator.

A comparable object can compare two objects. The class using Comparable interface, should implement the interface and override the abstract method compareTo(). The interface comes with only one abstract method and is a must to override when the interface is implemented.

  • int compareTo(Object obj): Compares two objects. With one object (current object) the method is called and the other is passed as parameter (like obj). The method returns an integer value depending on the objects under comparison as follows.
  1. positive value (more than 0) – when current object is greater than obj
  2. zero value – when current object equals obj
  3. negative value – when current object is less than obj

A program is given, Comparable Example, on Comparable interface where employees are sorted by their ages.

Also read Comparable vs Comparator for in depth understanding of using these interfaces.

Leave a Comment

Your email address will not be published.