Collections can be sorted in two ways, implementing Comparable or Comparator Interface.
Classes that implements Comparable, sorting is performed in the natural order.
But sometimes, we want to perform a different criteria for sorting, mostly user-defined type. Then we use Comparator.
Consider a class User, the most commonly found natural ordering would be order by lastName. This can implemented using Comparable interface, i.e.
Now to Sort the List of User objects..
Collections.sort (userList);
Coming to Comparator..I like using it..
..its Extensible,
To sort, you do the following.
Comparator comparator = UserFirstNameComparator.getInstance();
Collections.sort (userList, comparator);
While implementing Comparable you need to modify the class whose instances you want to sort. In Comparator, you will be creating an whole new class, making it reusable.
Comparator gives you the ability to sort objects is different ways and UNLIKE comparable you can use it sort instances of any other class(including the classes you dont have access to). Hence its extensible.
Looking at the code,
you should be able to figure out the remaining differences between them.
Try to make comparable and comparator work with TreeSet one at a time.
-Himalay