How does compareTo work?

I know that it compareToreturns a negative or positive result on how well one line correlates with another, but why:

public class Test {
    public static void main(String[] args) {
        String y = "ab2";
        if(y.compareTo("ac3") == -1) {
            System.out.println("Test");
        }
    }
}

true and

public class Test {
    public static void main(String[] args) {
        String y = "ab2";
        if(y.compareTo("ab3") == -1) {
            System.out.println("Test");
        }
    }
}

also right?

+4
source share
3 answers

The general contract Comparable.compareTo(o)is to return

  • a positive integer if it is larger than another object.
  • negative integer if it is less than another.
  • 0 if it is equal to another object.

In your example "ab2".compareTo("ac3") == -1, and "ab2".compareTo("ab3") == -1 means only that "ab2"is lower than "ac3"and "ab3". You cannot conclude anything regarding "ac3"and "ab3"only with these examples.

, b c ( "ab2" < "ac3") 2 3 (so "ab2" < "ab3"): Java .

+6

compareTo String -1, String (, ), String ( ) . "ab2" "ab3" ( , 2 - 3), "ac3" ( b c), -1.

+1

compareTo() . , "" , . :

  • ab2 <ac3 (because b <c)
  • ab2 <ab3 (because 2 <3)

By the way, you'd better use "<0" than "== -1" in an if statement, since the specification compareTosays that the function returns a negative number, not "-1"

+1
source

Source: https://habr.com/ru/post/1606295/


All Articles