Defining the criteria for sorting
Suppose we have list of Employees. We have to sort them. By default, you can't sort it, until you define some criteria. Say you define sorting as first name of employee, or you may say sort on the basis of employee id or their salary. So first thing is we have to define some criteria for sorting. This defines "natural ordering" on which sort can be done.
How to define "natural order" in java?
For this, we have to implement Comparable interface, which has compareTo method, which decides how we put natural ordering on the object.
Example:
Employee’s natural ordering would be done according to the employee id. For that, above Employee class must be altered to add the comparing ability as follows.
public class Employee implements Comparable<Employee> {
private int empId;
private String name;
private int age;
/**
* Compare a given Employee with this object.
* If employee id of this object is
* greater than the received object,
* then this object is greater than the other.
*/
public int compareTo(Employee o) {
return this.empId - o.empId ;
}
….
}
import java.util.*;
public class TestEmployeeSort {
public static void main(String[] args) {
List coll = Util.getEmployees();
Collections.sort(coll); // sort method
printList(coll);
}
private static void printList(List<Employee> list) {
System.out.println("EmpId\tName\tAge");
for (Employee e: list) {
System.out.println(e.getEmpId() + "\t" + e.getName() + "\t" + e.getAge());
}
}
}
Similarly to sort on the basis of name : write compareTo like this:
public int compareTo(Employee other) {
return name.compareTo(o2.getName());
//here compareTo() method of String is called
}
No comments:
Post a Comment