Comparable and Comparator in java with Example


package com.javaforecaset4u;
import java.util.*;
/*Class Using  Comparable */
class Employee implements Comparable{
int eid;
String ename;
String email;
public Employee(int eid, String ename,

String email) {
super();
this.eid = eid;
this.ename = ename;
this.email = email;
}
public String toString(){
return""+eid+"\t"+ename+"\t"+email;
}
public int compareTo(Object o){
Employee emp=(Employee)o;
return this.eid-emp.eid;
}
}
/*Class Using   Comparator  */
class NameCompator implements Comparator{
public int compare(Object o1,Object o2){
Employee e1=(Employee)o1;
Employee e2=(Employee)o2;
return e1.ename.compareTo(e2.ename);
}
}
/*Class Using   Comparator  */

class IDCompator implements Comparator{
public int compare(Object o1,Object o2){
Employee e1=(Employee)o1;
Employee e2=(Employee)o2;
return e1.eid-e2.eid;
}
}

public class JavaForeCast4U {

public static void main(String[] args) {

List list=new ArrayList();
Employee e1=new Employee(23, "kk", "kk@gmail");
Employee e2=new Employee(34,"aa","jj@gmail");
Employee e3=new Employee(12,"hh","yyq@gmail");
list.add(e1);
list.add(e2);
list.add(e3);

System.out.println("After Sorting By ID....");
Collections.sort(list);
Iterator it1=list.iterator();
while(it1.hasNext()){
System.out.println(it1.next());
}
System.out.println("sorting By Name...");
Collections.sort(list, new NameCompator());
Iterator it2=list.iterator();
while(it2.hasNext()){
System.out.println(it2.next());
}



}

}
OUTPUT
/*

After Sorting By ID....
12 hh yyq@gmail
23 kk kk@gmail
34 aa jj@gmail
sorting By Name...
34 aa jj@gmail
12 hh yyq@gmail
23 kk kk@gmail


*/

1 comment :