// The original Employee class:
public class Employee {
private int empId;
private String name;
private int age;
public Employee(int empId, String name, int age) {
// set values of fields
}
// getters & setters
}
import java.util.*;
public class Util {
public static ArrayList<Employee> getEmployees() {
ArrayList<Employee> col = new ArrayList<Employee>();
col.add(new Employee(5, "Frank", 28));
col.add(new Employee(1, "Jorge", 19));
col.add(new Employee(6, "Bill", 34));
col.add(new Employee(3, "Michel", 10));
col.add(new Employee(7, "Simpson", 8));
col.add(new Employee(4, "Clerk",16 ));
col.add(new Employee(8, "Lee", 40));
col.add(new Employee(2, "Mark", 30));
return col;
}
}
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) {
ArrayList coll = Util.getEmployees(); // use static Util.getEmployees()
Collections.sort(coll); // sort method
printList(coll);
}
private static void printList(ArrayList<Employee> list) {
System.out.println("EmpId\tName\tAge");
for (Employee e: list) {
System.out.println(e.getEmpId() + "\t" + e.getName() + "\t" + e.getAge());
}
}
}