Help coderanch get a
new server
by contributing to the fundraiser
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Comparator and Comparable

 
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


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

Thanks in advance !

 
Ranch Hand
Posts: 324
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks a lot Himalay !!
 
straws are for suckers. tiny ads are for attractive people.
We need your help - Coderanch server fundraiser
https://coderanch.com/t/782867/Coderanch-server-fundraiser
reply
    Bookmark Topic Watch Topic
  • New Topic