wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes comparable and compartor Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "comparable and compartor" Watch "comparable and compartor" New topic
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???
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: comparable and compartor
 
Similar Threads
inner class/inheritance
Multi Level Sorting of a ArrayList
Synchronization
How to compare to objects using comparator?
Multi Level Sorting of a ArrayList