• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Implementing Comparable

 
Nick Way
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
... 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
Pie
Posts: 24208
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Take a look at the "throws" part of the JavaDoc!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic