Comparable Interface in Java.

Java Comparable interface used to sort a array or list of objects based on their natural order. Natural ordering of elements is imposed by implementing it’s compareTo() method in the objects.This interface is found in java.lang package and contains only one method named compareTo(Object).
This ordering is referred to as the class’s natural ordering, and the class’s compareTo() method is referred to as its natural comparison method.

Using Comparable interface, we can sort the elements of:
  1. String objects.
  2. Wrapper class objects.ex: Integer, Long etc
  3. User defined custom objects.

compareTo(Object obj) method

 It is used to compare the current object with the specified object. It returns

  • positive integer, if the current object is greater than the specified object.
  • negative integer, if the current object is less than the specified object.
  • zero, if the current object is equal to the specified object.
Since this method is abstract, you must implement this method in your class if you implement the Comparable interface. A class  should implement the Comparable interface and override it’s compareTo() method. It must return a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.


Let’s see an example on how to implement the comparable interface:

class Employee implements Comparable<Employee>{
int empId;
String name;

Student(int empId,String name){
this.empId=empId;
this.name=name;
}
// overriding the compareTo method in the POJO class itself
public int compareTo(Employee emp){
if(empId==emp.empId)
return 0;
else if(empId>emp.empId)
return 1;
else
return -1;
}
}



Now Lets see the Implementation of the POJO example:

import java.util.*;
public class EmployeeSortExample{
public static void main(String args[]){
ArrayList<Employee> al=new ArrayList<Employee>();
al.add(new Employee(101,”Robert”));
al.add(new Employee(105,”Leonardo”));
al.add(new Employee(104,”Zeeshan”));

Collections.sort(al); //here compareTo is applied internally
for(Student st:al){
System.out.println(st.empId+” “+st.name+);
}
}

}  

Output:

101  Robert
104 Zeeshan
105 Leonardo