It's not a secret anymore!
The moose likes Beginning Java and the fly likes Comparable interface Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Comparable interface" Watch "Comparable interface" New topic

Comparable interface

Tom Bruner

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

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.

SCJP 1.4
Mike Curwen
Ranch Hand

Joined: Feb 20, 2001
Posts: 3695

return -1;
return 0;
return 1;

Michael Matola
Ranch Hand

Joined: Mar 25, 2001
Posts: 1793
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
Ranch Hand

Joined: Mar 25, 2001
Posts: 1793
Wow. Three people typing responses all at the same time!
I agree. Here's the link:
subject: Comparable interface
jQuery in Action, 3rd edition