Let’s understand the use of comparable interface in java with an example: We have an Employee class which has two attributes firstName and age. Now let’s look at how can we sort these Employee instances by salary? We can, of course, write our own code to sort them using any sorting algorithm, but the easy solution is to implement the java.lang.Comparable interface.
Here the Employee class implements the “java.lang.Comparable” interface and in turn implement the compareTo() method which returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object. This method will throw classCastException if the two objects are not instances of the Employee class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
public class Employee implements Comparable { private int sal; private String fistName; public int getSal() { return sal; } public void setSal(int sal) { this.sal = sal; } public String getFistName() { return fistName; } public void setFistName(String fistName) { this.fistName = fistName; } @Override public int compareTo(Object nextEmployee) { if(!(nextEmployee instanceof Employee)){ throw new ClassCastException("Invalid object"); } int sal = ((Employee) nextEmployee).getSal(); if(this.getSal() > sal) return 1; else if ( this.getSal() < sal ) return -1; else return 0; } @Override public String toString() { return this.sal+""; } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
public class TestComparable { public static void main(String[] args) { Employee emp1 = new Employee(); emp1.setSal(10000); Employee emp2 = new Employee(); emp2.setSal(30000); if(emp1.compareTo(emp2) > 0) { System.out.println("emp1 is getting more salary"); } else if(emp1.compareTo(emp2)< 0) { System.out.println("emp2 is getting more salary"); } else if(emp1.compareTo(emp2)== 0) { System.out.println("same salary"); } } } |
Output :
emp2 is getting more salary
Comparable interface to sort the Objects
We can sort the objects by using the comparable interface as below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
import java.util.ArrayList; import java.util.Collections; import java.util.List; public class ComparableDemo { public static void main(String[] args) { List empList = new ArrayList<Employee>(); Employee emp1 = new Employee(); emp1.setSal(10000); empList.add(emp1); Employee emp2 = new Employee(); emp2.setSal(45325); empList.add(emp2); Employee emp3 = new Employee(); emp3.setSal(7823); empList.add(emp3); Employee emp4 = new Employee(); emp4.setSal(45); empList.add(emp4); Employee emp5 = new Employee(); emp5.setSal(30000); empList.add(emp5); Collections.sort(empList); System.out.println(empList); } } |
Output
[45, 7823, 10000, 30000, 45325]