my dog learned polymorphism*
The moose likes Beginning Java and the fly likes can anybody tell about comparator in java Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "can anybody tell about comparator in java" Watch "can anybody tell about comparator in java" New topic
Author

can anybody tell about comparator in java

vijayakumar durai
Ranch Hand

Joined: Aug 18, 2008
Posts: 153
what is the use of comparator?what is the adavantage in comparator? can anybody give sample example?



thanks in advance
Vijitha Kumara
Bartender

Joined: Mar 24, 2008
Posts: 3827

You might use comparator for sorting the objects of the classes you are writing. Java API for Comparator has more details about it.


SCJP 5 | SCWCD 5
[How to ask questions] [Twitter]
Christophe Verré
Sheriff

Joined: Nov 24, 2005
Posts: 14687
    
  16

You'll find a detailed explanation here.


[My Blog]
All roads lead to JavaRanch
ramya narayanan
Ranch Hand

Joined: Oct 06, 2008
Posts: 338
Then what is the use of Comparable interface?
Gamini Sirisena
Ranch Hand

Joined: Aug 05, 2008
Posts: 347
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

Joined: Oct 13, 2005
Posts: 38497
    
  23
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: can anybody tell about comparator in java