| 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: 3670
|
|
|
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: 14672
|
|
|
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: 32689
|
|
|
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.
|
 |
 |
|
|
subject: can anybody tell about comparator in java
|
|
|