Java Reference
In-Depth Information
Did You Know?
Why Not - 1 , 0 , and 1 for compareTo ?
As we discussed earlier, some types like Integer return the values -1 , 0 , and 1
when you call compareTo . These are the canonical values for compareTo to
return, because they correspond to a function in mathematics known as the
signum function (sometimes abbreviated “sgn”). However, other types like
String do not return the standard values. You might wonder why Sun didn't
require that all classes return -1 , 0 and 1 when you call compareTo .
One answer to this question is that Java doesn't have a convenient ternary
type. For any binary decision, we can use boolean as the return type. But what
type do we use if we want to return exactly one of three different values? There
is no predefined type that has just three values, so it's more honest in a sense to
use Sun's rule that any negative number will do and any positive number will
do. Suppose that Sun said that compareTo should return only -1 , 0 , and 1 .
What should happen when someone writes a compareTo that returns some-
thing else? Ideally, any code calling that particular compareTo would throw an
exception when it gets an illegal return value, but that would require program-
mers to write a lot of error-checking code. By saying that all negatives will be
interpreted one way, all positives will be interpreted a second way, and 0 will
be interpreted a third way, Sun provided a complete definition for all values of
type int , which makes it easier for programmers to work with the compareTo
method.
A second reason for having compareTo behave this way is that it then is
easy to express many comparison tasks directly. It is often convenient to
express the comparison as a difference between two values. This pattern
occurs in many places. For example, the String class uses lexicographic
order (also called “dictionary” or “alphabetic” order). To determine the rela-
tionship between two String s, you scan through them until you find the first
pair of letters that differ. For example, if you were comparing "nattering"
and "nabobs" , you'd find that the first pair of characters that differ is the
third pair ( "nat..." versus "nab..." ). You would then return the differ-
ence between the character values ( ' t ' - ' b ' ). If you don't find such a pair,
then you return the difference between the lengths. For example,
"nattering" is considered greater than "nat" on the basis of length.
The compareTo behavior for the String class can be described with the fol-
lowing pseudocode:
search for a pair of characters in corresponding positions that differ.
if (such a pair exists) {
Continued on next page
Search WWH ::




Custom Search