File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Comparator and Comparable Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Comparator and Comparable" Watch "Comparator and Comparable" New topic

Comparator and Comparable

Ankit Dhebar

Joined: Feb 09, 2009
Posts: 16

Can anyone help me outwith comparator and comparable interfaces ?
With simple (easier) example !!
Please !!!

Thanks in advance !
Himalay Majumdar
Ranch Hand

Joined: Sep 28, 2008
Posts: 324
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.


SCJP 1.6, SCWCD 5.0, SCBCD 5.0 [loading..]
Ankit Dhebar

Joined: Feb 09, 2009
Posts: 16
Thanks a lot Himalay !!
I agree. Here's the link:
subject: Comparator and Comparable
It's not a secret anymore!