There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
But actually it seems to me, compareTo() returns only 0, 1, -1 even if the API spec does not explicitly mention it...So I could omit the transfomation which would reduce the amount of code. But, how can I be sure?
JavaBeginnersFaq
"Yesterday is history, tomorrow is a mystery, and today is a gift; that's why they call it the present." Eleanor Roosevelt
"I'm not back." - Bill Harding, Twister
Originally posted by Jim Yingst:
[MdQ]: I think you could easily write a test to see if '1' or '-1' is always returned.
True - however such a test may give misleading results. It's very common to see compareTo() methods which return only -1, 0, or 1, and therefore it's quite possible that a test will show that the method "always" returns those values. But that just means that the tester hasn't tried enough different Comparable classes. (Hint: try comparing two String values.)
....
If there is no index position at which they differ, then the shorter string lexicographically precedes the longer string. In this case, compareTo returns the difference of the lengths of the strings -- that is, the value:
this.length()-anotherString.length()
I recommend testing for the relationship to zero rather than a specific number.
So, one should always just check, if the returned value is equal to zero, higer than zero or lower than zero.
I'm THIS CLOSE to ruling the world! Right after reading this tiny ad:
Smokeless wood heat with a rocket mass heater
https://woodheat.net
|