In my previous post you would have learnt how to sort objects in a ArrayList using java comparator. Using the Comparable interface is almost the same as the previous, but here instead of a separate class for implementing the Comparator interface we can implement it in the same Employee Class by overriding the compareTo() method instead of the compare() method. Let see how the objects are sorted using the Comparable interface.
import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; public class SortObj { public static void main(String args[]) { List l = new ArrayList(); l.add(new Employee(20, "javainterviewpoint")); l.add(new Employee(10, "javainterview")); l.add(new Employee(30, "jip")); Collections.sort(l); System.out.println(l); } } class Employee implements Comparable { private String empname; private int eid; public Employee(int eid, String empname) { this.eid = eid; this.empname = empname; } public String getEmpname() { return empname; } public void setEmpname(String empname) { this.empname = empname; } public int getEid() { return eid; } public void setEid(int eid) { this.eid = eid; } public int compareTo(Employee e1) { // if this.eid is greater than e1's eid then it returns a positive // interger // if this.eid is lesser than e1's eid then it returns a negative // interger // if this.eid is equal than e1's eid then it returns zero return (this.getEid() - e1.getEid()); } public String toString() { return " \n id : " + this.eid + " empname : " + this.empname; } }
This will fetch you the sorted Employee Objects in ascending order as below
[ id : 10 empname : javainterview,
id : 20 empname : javainterviewpoint,
id : 30 empname : jip]
If you want the sorted list to be in descending order then just reverse the condition in the compareTo method from return (this.getEid() – e1.getEid()) to return (e1.getEid() – this.getEid()).
Leave a Reply