Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

can anybody tell about comparator in java

 
vijayakumar durai
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
 
Vijitha Kumara
Bartender
Pie
Posts: 3930
21
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.
 
Christophe Verré
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.
 
ramya narayanan
Ranch Hand
Posts: 338
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Then what is the use of Comparable interface?
 
Gamini Sirisena
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.
 
Campbell Ritchie
Sheriff
Posts: 51450
87
  • 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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic