aspose file tools*
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


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Implementing Comparable" Watch "Implementing Comparable" New topic
Author

Implementing Comparable

Nick Way
Greenhorn

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
Marshal

Joined: Jul 08, 2003
Posts: 24166
    
  30

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
author
Sheriff

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: http://aspose.com/file-tools
 
subject: Implementing Comparable
 
Similar Threads
Generics and collections K&B pg 526
Sublist
Searching for a list element without having to iterate
How does HashMap locate the correct value when multiple values are in the same bucket?
Overriding equals()