Comparable Interface in Java | Use, Example

Last Updated on January 12, 2021 by Scientech Easy

Comparable interface in Java defines compareTo() method for comparing objects of the same type.

In other words, Comparable interface defines a standard way in which two objects of the same class will be compared.

It is mainly used to provide the natural sorting order of objects (elements). The natural ordering means the usual ordering.

For example, the natural order of strings is alphabetical (i.e. A before B, B before C, and so on). For numeric values, it is numeric order (i.e. 1 before 2, 2 before 3, and so on).

Java Comparable interface can be implemented by any custom class or user-defined class if you want to use Arrays or Collections sorting methods.

The sorted collections use the natural sorting order defined by a class to determine the order of objects. So, if you want to store objects in a sorted collection, its class must implement Comparable interface.

Comparable interface was introduced in Java 1.0 version. It is present in java.lang.Comparable package and contains only one method named compareTo(Object).

When to use Comparable interface in Java?


Suppose we want to find the larger or smaller of two objects of the same type, such as two students, two employees, two dates, two rectangles, two squares, or two circles.

In order to compare it, the two objects must be comparable. To accomplish this purpose, Java provides Comparable interface.

The purpose of using Comparable interface and its compareTo() method is to compare one object with another object in a way less than (<), equal to (=), or greater than (>).


Look at the below realtime example to understand better.Comparable interface in Java

Comparable Interface declaration


Comparable in Java is a generic interface that can be declared like this in the general form:

public interface Comparable<T>

Here, T represents the type of objects that has to be compared. Several classes in Java library such as BigDecimal, BigInteger, Boolean, Byte, ByteBuffer, Calendar, String, etc implement Comparable interface in java to define a natural order for objects.

compareTo(Object obj) Method in Java


The Comparable interface provides only one abstract method that is used to determine the natural ordering of instances of a class. The signature of this method is as follows:

public int compareTo(Object obj)

// This method is defined in Comparable interface for comparing objects (defined in java.lang package) like this:
  package java.lang;
  public interface Comparable<E> {
      public int compareTo(Object obj);
  }

The compareTo() method is used to compare the current object with the specified object. It returns an indication that is as follows:

  • positive integer value, if the current object is greater than the specified object (this > object).
  • negative integer value, if the current object is less than the specified object (this < object).
  • zero, if the current object is equal to the specified object (this = object).

Let’s understand it with the following examples.

1. a.compareTo(b) must return a negative number if a should come before b, zero if a and b are the same, and a positive number if b should come before a.

2. System.out.println(new Integer(3).compareTo(new Integer(5))); must return a negative value becuase 3 is less than 5.

3. System.out.println(“ABC”.compareTo(“ABE”)); must retrun negative value becaue ABC is less than ABE.


4. java.util.Date date1 = new java.util.Date(2021, 1, 1);

java.util.Date date2 = new java.util.Date(2020, 1, 1);
System.out.println(date1.compareTo(date2)); must return a positive value because date1 is greater than date2.

Thus, numbers, strings, dates are comparable. We can use the compareTo() method to compare two numbers, two strings, and two dates.

In general, we can sort elements of String objects, Wrapper class objects, and User-defined class objects.

If the two objects are not compatible with each other, the compareTo() method will throw an exception named ClassCastException.

How to Implement Comparable Interface in Java with Example Programs


Several classes in the Java library implement Comparable interface to define a natural sorting order for objects. These classes are Byte, Short, Integer, Long, Float, Double, Character, BigInteger, BigDecimal, Calendar, String, Date, etc.

All these classes implement the Comparable interface. For example, the String, and Integer classes are defined as follows in the Java API:

1. public class String extends Object
        implements Comparable<String> {
      // class body omitted
    @Override
    public int compareTo(String o) {
      // Implementation omitted
      }
    }
2. public class Integer extends Number
         implements Comparable<Integer> {
      // class body omitted
   @Override
   public int compareTo(Integer o) {
     // Implementation omitted
    }
  }

Note: String and Wrapper classes implement Comparable interface by default.

1. Let’s take an example program where we will define a user-defined class Student that will implement Comparable interface to sort the list of elements on the basis of roll numbers. Look at the program source code to understand better.

Program source code 1:

public class Student implements Comparable<Student> {
// Declaration of variables.	
    String name;
    int rollno;   
    int age;  
Student(String name, int rollno,int age){
    this.name = name;
    this.rollno = rollno;  
    this.age = age;  
  }
// Compare two students based on their roll numbers.

@Override // Implementing the compareTo method defined in Comparable interface. 	  
public int compareTo(Student st)
{  
// Logic for sorting elements in ascending order.
 if(rollno == st.rollno)  
  return 0;  
	else if(rollno > st.rollno)  
	return 1;  
	else  
	return -1;  
   }  
}
import java.util.ArrayList;
import java.util.Collections;
public class TestNaturalOrder {
public static void main(String[] args) 
{
// Creates objects of Student class and passes the parameters to their constructors.
   Student st1 = new Student("John", 20, 15);
   Student st2 = new Student("Peter", 15, 16);
   Student st3 = new Student("Deep", 25, 15);
   
// Create an object of ArrayList of type Student.
   ArrayList<Student> al = new ArrayList<>();
  
// Adds elements (references) to the array list.
   al.add(st1);
   al.add(st2);
   al.add(st3);
 
// Display name of students, sorted by rollnos.
  System.out.println("Displaying student's name sorted by rollnos:");
  Collections.sort(al); // This method is used to sort elements of list. 
  for(Student st:al){  
       System.out.println(st.name+" "+st.rollno+" "+st.age);  
   }     
  }
 }
Output:
      Displaying student's name sorted by rollnos:
      Peter 15 16
      John 20 15
      Deep 25 15

2. Let’s take the same example program where we will sort the list of elements on the basis of rollnos in reverse order. We only need to change the particular code in the Student class.

Program source code 2:

public int compareTo(Student st)
{ 
// Logic for sorting elements in descending order or reverse order. 
 if(rollno == st.rollno)  
  return 0;  
	else if(rollno < st.rollno)  
	return 1;  
	else  
	return -1;  
 }

3. Let’s take one more example program where we will learn how to sort employee objects in java using comparable interface. This example program will clear all doubts of the comparable interface.

In this example program, we will create a class Employee that will implement Comparable interface and will sort employee information based on their hike salary.

Look at the following source code to understand better.

Program source code 3:

public class Employee implements Comparable<Employee> {
// Declaration of encapsulated variables.
  private String name;
  private double salary;
 
public Employee(String name, double salary){
  this.name = name;
  this.salary = salary;
  }
public String getName() {
   return name;
 }
public double getSalary() {
   return salary;
 }
public void hikeSalary(double byPercent){
  double hike = salary * byPercent / 100;
   salary += hike;
 }
@Override
public int compareTo(Employee emp)
{
 if (salary < emp.salary) return -1;
 if (salary > emp.salary) return 1;
   return 0;
  }
}
import java.util.Arrays;
public class EmployeeSortTest {
public static void main(String[] args) 
{
// Create an array. 
Employee[] staff = new Employee[3];
	staff[0] = new Employee("Harry", 30000);
	staff[1] = new Employee("Carl", 70000);
	staff[2] = new Employee("Tony", 39000);
	
  Arrays.sort(staff); //  This method is used to sort list of elements in Arrays.
  
// Display information about all Employees, sorted by their salaries.
  for (Employee e : staff)
     System.out.println("name: " + e.getName() +", "+"salary = " + e.getSalary());
    }
}
Output:
      name: Harry, salary = 30000.0
      name: Tony, salary = 39000.0
      name: Carl, salary = 70000.0

Hope that this tutorial has covered the basic points of Comparable interface in Java with realtime examples and programs. I hope that you will have understood how to use and implement comparable interface.
Thanks for reading!!!