Comparable interface in java

Let’s learn comparable interface in java.

Comparable interface in java

Comparable interface is present in java.lang package and it contains only one method compareTo().

Declaration:

public interface Comparable<T>

Parameters:

<T> the type of objects that this object may be compared to.


compareTo(Object obj) method

Declaration:

public int compareTo(Object obj)

Parameters:

obj the object to be compared.

compareTo method returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.

The compareTo() method is used to compare objects which returns,

  • Positive number if first object is greater than the second object.
  • Zero if first object is equal to second object.
  • Negative number if first object is less than the second object.

Here’s an example on compareTo() method in java.

class CompareToExample
{
   public static void main(String[] args)
   {
      System.out.println("B".compareTo("Y"));
      System.out.println("Y".compareTo("B"));
      System.out.println("B".compareTo("B"));
      System.out.println("B".compareTo(null));
   }
}

Output:

-23
23
0
Exception in thread “main” java.lang.NullPointerException
at java.base/java.lang.String.compareTo(String.java:1205)
at CompareToExample.main(CompareToExample.java:8)]


Let’s see example on comparable interface where instance variable “empAge” is sorted in ascending order.

class Employee implements Comparable<Employee>
{
   int empID;
   String empName;
   int empAge;
   Employee(int empID, String empName, int empAge)
   {
      this.empID = empID;
      this.empName = empName;
      this.empAge = empAge;
   }
   public int compareTo(Employee emp)
   {
      if(empAge == emp.empAge)
      {
         return 0;
      }
      else if(empAge > emp.empAge)
      {
         return 1;
      }
      else
      {
         return -1;
      }
   }
}
import java.util.ArrayList;
import java.util.Collections;

public class ComparableExample
{
   public static void main(String[] args)
   {
      ArrayList<Employee> al = new ArrayList<Employee>();
      al.add(new Employee(7056,"virat", 25));  
      al.add(new Employee(7158,"amit", 28));  
      al.add(new Employee(7263,"jay", 20));     
      Collections.sort(al);
      for(Employee obj : al)
      {  
         System.out.println(obj.empID + " " + obj.empName + " " + obj.empAge);
      }
   }
}

Output:

7263 jay 20
7056 virat 25
7158 amit 28


Also read – classes and objects in java