Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Comparable interface

 
Tom Bruner
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2205
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Mike Curwen
Ranch Hand
Posts: 3695
IntelliJ IDE Java Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
return -1;
return 0;
return 1;

 
Michael Matola
whippersnapper
Ranch Hand
Posts: 1817
4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1817
4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Wow. Three people typing responses all at the same time!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic