| Author |
Comparable interface
|
Tom Bruner
Greenhorn
Joined: Feb 12, 2002
Posts: 2
|
|
I have a question regarding Comaparable interface. When you implement the interface to a specific class, you must then override the comparTo() method, correct? The method requires that you pass an Object to it. So how do you return an int from something that gets passed an object?
|
 |
Rob Ross
Bartender
Joined: Jan 07, 2002
Posts: 2205
|
|
compareTo() is an instance method, so you can only call it on objects that support that method. When you do that, you pass an Object of the same type to the method, and then the method compares the two objects and returns an int representing how the objects compare to each other: a negative int if the object is "less" than the object in the paramater, a zero if they are equal, or a positive int if it is greater. By returning an int you are representing the ordering of the two objects. For numbers this would seem trivial, but for other types of objects you can determine your own custom order. For example, you could create a class that knows how to order the following titles by rank :greenhorn, ranch hand, bartender, sherrif. If I create a new User object say, User a = new User("ranch hand"); User b = new User("bartender"); assuming user implements Comparable, if I wrote int i = a.compareTo(b); i should get the value -1, a negative number, because ranch hand is "less than" a bartender (no offense to us ranch hands) If I wrote int i = b.compareTo(a); then i would get 1 , a positive number, because a bartender is "greater than" a ranch hand. And if I wrote int i = a.compareTo(a); i should get zero, because the two objects are equal in value.
|
Rob
SCJP 1.4
|
 |
Mike Curwen
Ranch Hand
Joined: Feb 20, 2001
Posts: 3695
|
|
return -1; return 0; return 1;
|
 |
Michael Matola
whippersnapper
Ranch Hand
Joined: Mar 25, 2001
Posts: 1721
|
|
Take a look at the compareTo( Object object ) (and variously overloaded) method(s) of java.lang.String or (easier) any of the wrapper classes such as java.lang.Integer for ideas on how to write a compareTo() method. For ideas on Comparable, see how String.CASE_INSENSITIVE_ORDER. It's not necessary to understand *all* the gory details of these to get a feel how to implement Comparable or Comparator, but they do give you a general picture.
|
 |
Michael Matola
whippersnapper
Ranch Hand
Joined: Mar 25, 2001
Posts: 1721
|
|
|
Wow. Three people typing responses all at the same time!
|
 |
 |
|
|
subject: Comparable interface
|
|
|