Monday, July 19, 2010

Comparable,Comparator - sample

package com;

import java.io.Serializable;
import java.util.Comparator;

@SuppressWarnings("serial")
public class Emp implements Comparable, Comparator , Serializable {

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.
*/


@Override
public int compareTo(Emp arg0) {
if (!(arg0 instanceof Emp))
throw new ClassCastException("A Person object expected.");

return this.getName().compareTo(arg0.getName()) ;
}



public Emp(int empId, String name, int age) {
this.empId = empId;
this.name = name;
this.age = age;
}

public int getEmpId() {
return empId;
}

public String getName() {
return name;
}

public int getAge() {
return age;
}

@Override
public int compare(Emp arg0, Emp arg1) {

return arg0.compareTo(arg1);

}

public static Comparator> nameComparator 
                          = new Comparator>() { 
public int compare(Emp emp1, Emp emp2) {
String name1 = emp1.getName().toUpperCase();
String name2 = emp2.getName().toUpperCase();
//ascending order
return name1.compareTo(name2);
 //descending order
//return name2.compareTo(name1);
	    }
 
	};

}
---------------------------------------------------
package com;

import java.util.ArrayList;
import java.util.List;

public class Util {

public static List getEmployees() {

List col = new ArrayList();

col.add(new Emp(5, "Frank", 28));
col.add(new Emp(1, "Jorge", 19));
col.add(new Emp(6, "Bill", 34));
col.add(new Emp(3, "Michel", 10));
col.add(new Emp(7, "Simpson", 8));
col.add(new Emp(4, "Clerk",16 ));
col.add(new Emp(8, "Lee", 40));
col.add(new Emp(2, "Mark", 30));

return col;
}

}
------------------------------------------

package com;

import java.util.Collections;
import java.util.List;

public class TestEmployeeSort {

/**
* @param args
*/
@SuppressWarnings("unchecked")
public static void main(String[] args) {

List coll = Util.getEmployees();
//Collections.sort(coll);
//use Comparator implementation
Collections.sort(coll);

//Arrays.sort(coll , Emp.nameComparator);
printList(coll);
}

private static void printList(List list) {
System.out.println("EmpId\tName\tAge");
for (Emp e: list) {
System.out.println(e.getEmpId() + "\t" + e.getName() + "\t" + e.getAge());
}
}

}
--------------------------------------

No comments: