Sorting using Comparable or Comparator
Of late, I've been involved in taking some interviews. Many of the candidates seem to be confused about the very simple concept of Comparator and Comparable. Comparable is an interface in which the contract is to provide your implementation of compareTo() method. For example:
// compares on the basis of last name class MyVO implements Comparable{
private String firstName; private String lastName; ... public int compareTo(Object o){ return lastName.compareTo(((MyVO)o).getLastName()); }
... }
Whereas, Comparator is similar to the C concept of function pointers (functors). In Java, we incorporate this by defining a class which implements Comparator, and overriding compare() method. If we think a bit broad, we can relate to Strategy design pattern -- provide different Comparator implementations for different situations. For example, you could switch from sorting on the basis of firstName instead of
lastName at runtime, based upon user-input.
A comparator implementation is as follows.
class LastNameComparator implements Comparator{
public int compare(Object o1, Object o2){ return ((MyVO)o1).getLastName().compareTo(((MyVO)o2).getLastName()); }
}
Once this is done, there are numerous ways in which you could sort your Collection.