Comparable
is generic and is declared as shown below.
public interface Comparable<T>
Here, T represents the type of objects being compared. If any class implement
Comparable
interface in Java then collection of that object either
List
or
Array
can be sorted automatically by using
Collections.sort()
or
Arrays.sort()
method and object will be sorted based on there natural order defined by
CompareTo
method.
Comparable interface have
compareTo
method to compare objects.
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);
}
}
OUTPUTDisplaying 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]
DESCRIPTIONIn 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
- Try to sort the list with respect to
age
in the ascending order use the below sample code.
return age - o.age;