Letting the class implement the Comparable
interface, as suggested in the other answers, is one option.
But in general, I'd recommend to NOT implement the Comparable
interface, as long as the class does not have an undoubted natural ordering. And for Employee
, there is certainly NO natural ordering.
Imagine you want to sort the Employees according to their age. Once in ascending order, and once in descending order. How could you do that? Now imagine you want to sort them once by their age, and once alphabetically, by their first name. You could not do this, without implementing a Comparator
. And that's what I'd recommend here:
You can create a method like
private static Comparator<Employee> byAge()
{
return new Comparator<Employee>()
{
@Override
public int compare(Employee o1, Employee o2)
{
return o1.getAge() - o2.getAge();
}
};
}
Then you can simply call
Collections.sort(empList, byAge());
If you want to sort them in reverse order, you can call
Collections.sort(empList, Collections.reverseOrder(byAge()));
If you want to sort them by their name, you can create a method
private static Comparator<Employee> byName()
{
return new Comparator<Employee>()
{
@Override
public int compare(Employee o1, Employee o2)
{
return o1.getName().compareTo(o2.getName());
}
};
}
And sort them with
Collections.sort(empList, byName());
This is much more versatile than implementing Comparable
.