Forums Register Login

Implementing Comparable

+Pie Number of slices to send: Send
... 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.
+Pie Number of slices to send: Send
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.
+Pie Number of slices to send: Send
Take a look at the "throws" part of the JavaDoc!
Doody calls. I would really rather that it didn't. Comfort me wise and sterile tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 622 times.
Similar Threads
Generics and collections K&B pg 526
How does HashMap locate the correct value when multiple values are in the same bucket?
Sublist
Overriding equals()
Searching for a list element without having to iterate
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 14:54:19.