28 February 2011

How to use Comparator and Comparable in Java. Comparable Vs Comparator battle

So...  I was told that using   Comparable and Comparator in the same class is a bad  .
I've done it,because ... Eclipse suggest me this silly idea. It obviously means that i didn't understand difference between them,so it was time for do little research  and here are my notes:


A comparable is a interface and object that implement this interface is capable of comparing itself with another object. To implement this  interfaced class must contain a method called compareTo.

A comparator object is capable of comparing two different objects. The class is not comparing its instances, but some other class’s instances. This comparator class must implement the java.util.Comparator interface.

Look for below links for more complete information about  Comparable and Comparator: (Where they will show example how to implementing sorting for  List and other collections ):
java sorting - comparator vs comparable
javablogging - comparable vs comparator