How does compareTo work?

不羁的心 提交于 2019-12-10 02:25:17

问题


I know that compareTo returns a negative or positive result on how well one string correlates to the other, but then why:

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

is true and

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

is also true?


回答1:


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

  • a positive integer if this is greater than the other object.
  • a negative integer if this is lower than the other object.
  • 0 if this is equals to the other object.

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

This result is expected since b comes before c in the alphabet (so "ab2" < "ac3") and 2 comes before 3 (so "ab2" < "ab3"): Java sorts Strings lexicographically.




回答2:


compareTo for Strings returns -1 if the first String (the one for which the method is called) comes before the second String (the method's argument) in lexicographical order. "ab2" comes before "ab3" (since the first two characters are equal and 2 comes before 3) and also before "ac3" (since the first character is equal and b comes before c), so both comparisons return -1.




回答3:


compareTo() compares two string with regard to their alphabetical order. Both of you tests have a String that is alphabetically sorted "before" the String you compare it with. In other words:

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

By the way, you should rather use "< 0" than "== -1" in your if statement, as the compareTo spec says that the function returns a negative number, not specifically "-1"



来源:https://stackoverflow.com/questions/32443402/how-does-compareto-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!