Here is a compare method of a Comparator
class AgeComparator implements Comparator{
public int compare(Object emp1, Object emp2){
/*
* parameter are of type Object, so we have to downcast it
* to Employee objects
*/
int emp1Age = ((Employee)emp1).getAge();
int emp2Age = ((Employee)emp2).getAge();
if(emp1Age > emp2Age)
return 1;
else if(emp1Age < emp2Age)
return -1;
else
return 0;
}
}
Question: How does these return makes a list in ascending / descending order ?
We use the above comparator this way.
//Employee array which will hold employees
Employee employee[] = new Employee[2];
//set different attributes of the individual employee.
employee[0] = new Employee();
employee[0].setAge(40);
employee[0].setName("Joe");
employee[1] = new Employee();
employee[1].setAge(20);
employee[1].setName("Mark");
//Sorting array on the basis of employee age by passing AgeComparator
Arrays.sort(employee, new AgeComparator());