| Author |
comparable and compartor
|
akash azal
Ranch Hand
Joined: Jan 31, 2009
Posts: 70
|
|
what is the difference between comparable and comparator.
when we use comparable and when we use comparator.
) both return int
in comparator
eg. int r=compare(obj1.obj2);
in comparable
eg. int r=obj1.compareTo(obj2);
ii)both returns
negative if obj1<obj2
zero if obj1==obj2
positive if obj1>obj2
am i right
|
We will keep things moving!!
|
 |
pete stein
Bartender
Joined: Feb 23, 2007
Posts: 1561
|
|
You speak of these interfaces as if they are methods. They are not. They are interfaces that encapsulate the same idea but in a subtly different way. A class is made to implement the Comparable interface if it has a natural way of ordering itself, for instance if you had a class to hold student information and if you would typically order this information based on the student's name, then you would make the class Comparable and have the compareTo method of the object compare last names followed by first names (if last names were equal). If on the other hand you had a class of Student information, but would typically order this in many different ways -- name, or grade, or student ID number, perhaps, then you would create separate Comparator classes (these are helper classes) that define each ordering that may be needed. Then when you wish to sort your listed Student information, you'd use an appropriate Comparator helper object in your call to the sort method.
Also note how the compareTo vs compare methods are different in that one has one parameter and the other has two.
Best of luck and hth.
|
 |
akash azal
Ranch Hand
Joined: Jan 31, 2009
Posts: 70
|
|
|
thanks for clearing doubt
|
 |
Balaji Bang
Ranch Hand
Joined: Apr 23, 2007
Posts: 180
|
|
I didnot understand how the return values in compare and compareTo will effect the order of a collection.
Anyone please explain..
|
 |
akash azal
Ranch Hand
Joined: Jan 31, 2009
Posts: 70
|
|
difference between return types
public static <T extends Comparable<? super T>> void sort(List<T> list)
public static <T> void sort(List<T> list,
Comparator<? super T> c)
|
 |
Balaji Bang
Ranch Hand
Joined: Apr 23, 2007
Posts: 180
|
|
How these methods will be used in sorting a list and for a TreeSet???
|
 |
 |
|
|
subject: comparable and compartor
|
|
|