Tuesday, December 1, 2009

comparable or comparator

Comparable or Comparator which of these interfaces to use and when; I had been thinking hard on this for quite sometime and had a discussion with a friend of mine on it..
Well here s the tip: use Comparator Interface when instances of your class can be compared in more than one way, else go with Comparable interface. For eg. Employees of a company can be compared by their name, age, salary, etc... So you could define a comparator for each of these criterions and pass it to the static sort method of ArrayList.
Refer http://onjava.com/onjava/2003/03/12/java_comp.html for more clarity.

No comments: