Link to home
Start Free TrialLog in
Avatar of yattias
yattias

asked on

comparable interface and compareTo method

You use the compareTo method to compare two objects right? How come sometimes before comparing the objects it is necessary to type cast them to type Comparable?  (Comparable)obj
ASKER CERTIFIED SOLUTION
Avatar of BogoJoker
BogoJoker

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Siva Prasanna Kumar
http://www.developer.com/java/article.php/858411

Just check out all the 3 parts.

I don't think that kind of Type casting is required as many classes already implement if for exacmple check out String Class it a Comparable Object.
Avatar of yattias
yattias

ASKER

thanks, what I meant was really in general, why would you type cast an object to Comparable? is it so it will include the comparable interface for incase it does not?
> why would you type case an object to Comparable
To ensure that the object your casting has a compareTo method.

Look at the Object class definition.  It has what, 10 methods?
wait, clone, toString, notifyAll, notify, hashCode, getClass, finalize, equals

None of those are compareTo.  If you do this:
Object obj = new Object();
obj.compareTo(new Object());

Then the compiler will say I don't see a compareTo method.  You have a problem!
Type casting it to a Comparable ensures the compiler that the compareTo is defined in the object.
Joe P