... 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
staff
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.