File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Implementing Comparable Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Implementing Comparable" Watch "Implementing Comparable" New topic

Implementing Comparable

Nick Way

Joined: Feb 06, 2004
Posts: 7
... or in particular, the method . The ordinary logic of this is clear - return -1, 0, or 1 according to how the two objects compare in whatever way you define, but what if the passed object is not the same class? Should you just throw an Exception and expect the calling program to deal with it? And if not, what would be a logical thing to return. The reason I ask is that would presumably return false (rather than throwing an Exception) if the obejct wasn't the same class.
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199

If you look at the java.util.Comparable Javadoc, you'll see that compareTo() is actually declared to throw ClassCastException in this case. So the proper thing to do is generally just to write the method as if the argument were of the correct type, and allow nature to take its course.

[Jess in Action][AskingGoodQuestions]
Ilja Preuss

Joined: Jul 11, 2001
Posts: 14112
Take a look at the "throws" part of the JavaDoc!

The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
I agree. Here's the link:
subject: Implementing Comparable
It's not a secret anymore!