This week's book giveaway is in the Clojure forum.
We're giving away four copies of Clojure in Action and have Amit Rathore and Francis Avila on-line!
See this thread for details.
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Comparator and Comparable

 
Ankit Dhebar
Greenhorn
Posts: 16
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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

Thanks in advance !
 
Himalay Majumdar
Ranch Hand
Posts: 324
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Ankit Dhebar
Greenhorn
Posts: 16
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot Himalay !!
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic