Comparable Example Java

Before going through this program, it is advised to go through the interface Comparable tutorial.

In the following Employee program, compareTo() method of Comparable interface is used to sort the employees by their ages. To use the compareTo() method, Employee class implements Comparable interface.

Example code on Comparable Example
import java.util.*;
class Employee implements Comparable
{
  int age;
  String department;
  public Employee(int age, String department)
  {
    this.age = age;
    this.department = department;
  }
  public int getAge()
  {
    return age;
  }
  public String getDepartment()
  {
    return department;
  }
  public int compareTo(Employee emp) 
  {
    return this.age - emp.age;
  }
}

public class EmployeeExample
{
  public static void main(String args[])
  {
    ArrayList employeeList = new ArrayList();
    employeeList.add(new Employee(55, "Finance"));
    employeeList.add(new Employee(44, "HR"));
    employeeList.add(new Employee(22, "Inventory"));
    employeeList.add(new Employee(33, "Accounts"));

    Collections.sort(employeeList);
  
    System.out.println("\nAge\tDepartment\n");
    for (Employee st : employeeList) 
    {
      System.out.println(st.getAge() + "\t" + st.getDepartment());
    }
  }
}


Comparable Example
Output screenshot on Comparable Example

     class Employee implements Comparable

An Employee class implementing generics Comparable interface is declared. Here generics means, a Comparable object compares only Employee objects. Two instance variables (also known as fields) age and department are declared and through the constructor their values are assigned. Two gettter methods (getAge() and getDepartment()) are also declared with which the field values can be retrieved later.

     public int compareTo(Employee emp) 
     {
       return this.age - emp.age;
     }

The Employee class overrides the abstract method of Comparable interface, compareTo() method. The Employee objects are sorted as per the age field. The keyword "this" refers the Employee object with which the compareTo() method is called and emp refers the Employee object we are passing as parameter.

     public class EmployeeExample

One more class EmployeeExample is created that creates a number of Employee objects and sorts.

     ArrayList employeeList = new ArrayList();
     employeeList.add(new Employee(55, "Murthy"));

A generics ArrayList object employeeList is created and populated with a few elements (here, elements are Employee objects) with add() method.

     Collections.sort(employeeList);

The Comparable interface should be used with the sort() method of Collections class. Now the sort() method sorts employeeList as the per the Comparator's compareTo() method.

     for (Employee st : employeeList) 
     {
       System.out.println(st.getAge() + "\t" + st.getDepartment());
     }

With enhanced for loop, all the employees ages and departments are printed. Observe, the ages are printed in ascending order.

Another program on Comparable is available at Comparable vs. Comparator.

Requires lot of practice to have command over "Comparable Example".

11 thoughts on “Comparable Example Java”

  1. Madhava Nandan Rao

    Hello sir,
    I am your student in nexwave. Java 22 batch..
    In the aboive code, what is happening in compareTo(),
    How “this” is working in that? I mean can you explein the compareTo().

    And if we remove Comparable and compareTo(), Then Collections.sort() is showing some error.. Is there any link between them?

    Thank you sir..

    1. compareTo() does lexicographical comparison. It takes one-by-one characters from each string and then compares. Returns the difference of ASCII values of the two characters. When dissimilar characters pair is encountered once, the comparison terminates. It is given in my way2java.com

      Before using compareTo() etc. the elements must be sorted with sort() method. This is also given in my site way2java.com.

      1. public int compareTo(Employee emp)
        {
        return this.age – emp.age;
        }
        where are we calling this method in the above program by passing emp as parameter.plz rectify how are employee objects are sorted based on compareTo() method?

  2. HI sir how to use compareTo() method to compare 4 different fields in one object i.e
    1.name and rollno
    2.branch and name like can u have an example for this?

  3. public int compareTo(Employee emp)
    {
    return this.age – emp.age;
    }
    where are we calling this method in the above program by passing emp as parameter.plz rectify how are employee objects are sorted based on compareTo() method?

Leave a Comment

Your email address will not be published.