Java Comparable compareTo Method Usage
We need to implement the Comparable Interface, if we have to sort user defined objects in Java. The compatable interface has a compareTo() method that is used by the sort() method of the Array’s Class.
In this code Employee class is implementing Comparable interface and overridden the compareTO() method. The ComparableDemo.java class uses the Arrays.sort(any comparableObject) which internally uses the compareTo() method of Employee class and sorts the Employees.
[sourcecode language='java']
import java.util.Arrays;
class Employee implements Comparable {
private int empId;
private String name;
public Employee(int id, String name) {
this.empId = id;
this.name = name;
}
public int getEmpId() {
return empId;
}
public void setEmpId(int empId) {
this.empId = empId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int compareTo(Object o) {
Employee obj = (Employee) o;
if (this.getEmpId() < obj.getEmpId()) {
return -1;
} else if (this.getEmpId() > obj.getEmpId()) {
return 1;
}
return 0;
}
public String toString() {
return name;
}
}
public class ComparableDemo {
public static void main(String[] args) {
// Sorting the Employees based on Emplyee ID
Employee[] emps = new Employee[3];
emps[0] = new Employee(10, “Bob”);
emps[1] = new Employee(30, “Sob”);
emps[2] = new Employee(20, “Rob”);
System.out.println(”Employees are : ” + emps[0] + “\t” + emps[1] + “\t”
+ emps[2]);
Arrays.sort(emps);
System.out.println(”Employees are : ” + emps[0] + “\t” + emps[1] + “\t”
+ emps[2]);
}
}
[/sourcecode]











Leave a Reply