Menu
Topics Index
...
`

ComparableInterfaceDemo - Java Example Program


ComparableInterfaceDemo
import java.util.*;

class Employee implements Comparable<Employee>
{
    String name;
    int age;
    int experience;
    
    public Employee(String name, int age, int experience) // LINE A
    {
        this.name = name;
        this.age = age;
        this.experience = experience;
    }
    
    public String toString() // LINE B
    {
        return "Name : " + name + " Age : " + age + " Experience : " + experience;
    }
    
    public int compareTo(Employee o) // LINE C
    {
        return experience - o.experience;
    }
}

public class ComparableInterfaceDemo
{

    public static void main(String[] args)
    {
        ArrayList list = new ArrayList(); // LINE D
        list.add(new Employee("Siva", 35, 12));
        list.add(new Employee("Maheesh", 25, 3));
        list.add(new Employee("Narayan", 26, 2));
        list.add(new Employee("Srinath", 24, 3));
        System.out.println(list); // LINE E
        Collections.sort(list); // LINE F
        System.out.println(list);
    }
}
OUTPUT

Displaying unsorted list :
[Name : Siva Age : 35 Experience : 12, Name : Maheesh Age : 25 Experience : 3, Name : Narayan Age : 26 Experience : 2, Name : Srinath Age : 24 Experience : 3]
Displaying sorted list :
[Name : Narayan Age : 26 Experience : 2, Name : Maheesh Age : 25 Experience : 3, Name : Srinath Age : 24 Experience : 3, Name : Siva Age : 35 Experience : 12]

DESCRIPTION

In the above program we demonstrated how to compare two objects using Comparable interface. Firstly we have created Employee class which implements Comparable interface and declared three variables name, age, experience. At LINE A we have created a constructor to assign values to Employee objects. At LINE B we implemented toString method to return the output. At LINE C implemented compareTo method of Comparable interface to compare two Employee objects and we have created the main class CompareInterfaceDemo. At LINE D we have created an ArrayList and added Employee objects to it. At LINE E we are displaying the unsorted list. At LINE F we are sorting the list with respect to the Employee field experience. When Collections.sort(list) is executed it automatically calls the Comparable's compareTo method and depending on the return value it sorts the list.

THINGS TO TRY
  • At LINE C in compareTo method replace the code with the below code to sort the list in descending order.
    return o.experience - experience;
  • Try to sort the list with respect to age in the ascending order use the below sample code.
    return age - o.age;
  • Try to sort the list with respect to name in the descending order use the below sample code.
    return name.compareTo(o.name);

© meritcampus 2019

All Rights Reserved.

Open In App