Win a copy of Learning OpenStack Networking: Build a solid foundation in virtual networking technologies for OpenStack-based clouds this week in the Cloud/Virtualization forum!
  • 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Liutauras Vilda
  • Campbell Ritchie
  • Tim Cooke
  • Bear Bibeault
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Knute Snortum
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Ganesh Patekar
  • Stephan van Hulst
  • Pete Letkeman
  • Carey Brown
Bartenders:
  • Tim Holloway
  • Ron McLeod
  • Vijitha Kumara

can anybody tell about comparator in java  RSS feed

 
Ranch Hand
Posts: 153
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
what is the use of comparator?what is the adavantage in comparator? can anybody give sample example?



thanks in advance
 
Bartender
Posts: 4050
54
Chrome Fedora Hibernate
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You might use comparator for sorting the objects of the classes you are writing. Java API for Comparator has more details about it.
 
Sheriff
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You'll find a detailed explanation here.
 
Ranch Hand
Posts: 338
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Then what is the use of Comparable interface?
 
Ranch Hand
Posts: 378
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A class that implements Comparable is sortable. It can be sorted according to the implemented compareTo method using the Comparable mechanism. This is called the Class's natural ordering.

Suppose you want to sort objects of this class based on some other criteria. Then you can create an implementation of a Comparator and use that. You can create yet another Comparator to sort it based on some other criteria.

Also when you want to define a sort order for a non Comparable object (i.e has not implemented Comparable) you can use a Comparator or many.

For example for a Job object having members jobID and priority, two Comparators can be implemented, one sorting on jobID and the other on priority.
 
Marshal
Posts: 60069
188
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You implement Comparable<T> on a class which has a "natural order;" Integer implements it because you can order numbers 1 2 3 and String implements it because you can order Strings alphabetically.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!