| Author |
Comparable and comparator interface
|
jose chiramal
Ranch Hand
Joined: Feb 12, 2010
Posts: 266
|
|
In java.util.collection which are the classes that implement Comparable and which ones implement Comparator ?
Can i say classes that implement Comparable impose natural order ??
|
 |
Sebastian Janisch
Ranch Hand
Joined: Feb 23, 2009
Posts: 1183
|
|
Question 1: A quick look into the API helps identifying the interfaces implemented by a class.
Question 2: Comparator and Comparable are two different approaches for doing the same thing.
The Comparable interface is used to mark a class as Comparable. It is like saying 'Hello my name is ClassX and I am Comparable'. A Set or whatever structure you use checks for the class being Comparable and uses the logic implemented in it's compareTo method.
Comparator is an interface that I consider as a little more abstract. You can define general sorting patterns you need to use. Let's say you have a Person object. Comparable let's you only sort in one specific way, but you can create many Comparator implementations and use them for sorting the Person class any way you like, you just have to pass an instance to the sort method.
|
JDBCSupport - An easy to use, light-weight JDBC framework -
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32689
|
|
|
Look in the API for Comparable and Comparator and it may tell you "known implementing classes", so you can find out there.
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19216
|
|
jose chiramal wrote:Can i say classes that implement Comparable impose natural order ??
That is the term used by Sun in their Javadoc of TreeMap among others:
Constructs a new, empty tree map, using the natural ordering of its keys. All keys inserted into the map must implement the Comparable interface. Furthermore, all such keys must be mutually comparable: k1.compareTo(k2) must not throw a ClassCastException for any keys k1 and k2 in the map.
|
SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
|
 |
jose chiramal
Ranch Hand
Joined: Feb 12, 2010
Posts: 266
|
|
|
I just went through some books , Only TreeSet and TreeMap actually have compareTo() as the method called on their elements.
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19216
|
|
|
Are you sure? Inside the Collection framework probably yes, but not in Java. In Java you can use them for just about anything, like checking if one date comes before another one.
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32689
|
|
|
But the original question said "in java.util.collection" (sic).
|
 |
 |
|
|
subject: Comparable and comparator interface
|
|
|