The compareTo
method of the String
class is used to sort the String
s alphabetically *, not by size. In this way we have "araraaaaaa"
comes before "asa"
, and therefore compareTo
gives -1, because when comparing the first letter the two String
s are equal ( a
) and when comparing the second, r
comes before s
.
To compare the% s of% s by size, you should invoke the String
method of length
s and then compare the sizes directly. (Suggested Marcelo Bonifazio )
It is also worth remembering that whenever we have String
returning -1 (or some other negative number) it means that a.compareTo(b)
precedes a
, if it returns +1 (or some other positive number) then b
happens a
and if it returns 0 then b
and a
are similar. However, the exact definition of "precede", "succeed" and "similar" is at the discretion of each class that implements b
. In the case of class compareTo
the definition is given by the alphabetical order *.
(*) - Actually the comparison is not exactly alphabetic, but is based on the comparison of sequences of numeric values of unicode codepoints.