Doubt with the compareTo function

3

When I run the code below the compareTo returns a value less than zero.

public class compare
{
 public static void main ( String [] args )
 {
    String str1 = "araraaaaaa";  
    String str2 = "asa";  

    int comp = str1.compareTo(str2);  

    System.out.println(""+comp) //  printa -1 na tela

 }
}

Theoretically, str1 is not greater than str2 ? Why does it return negative?

    
asked by anonymous 13.02.2015 / 03:49

1 answer

6

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.

    
13.02.2015 / 03:57