Java 这种情况下 CompareTo 函数的作用是什么

What does the CompareTo function do in this situation in Java

public static void main(String[] args) {
     System.out.print("Comparing \"axe\" with \"dog\" produces ");
     // I don't understand what this does.
     int i = "axe".compareTo("dog");
     System.out.println(i);

     System.out.print("Comparing \"applebee's\" with \"apple\" produces ");
     // neither this.
     System.out.println( "applebee's".compareTo("apple") );


}

当我运行代码出来的是-3,下一个是5, 我不明白你怎么能比较字母和数字。 "applebee" 和 "dog" 甚至不是字符串变量 这是 this link

学校的作业

compareTo 返回的 特定数字 是您应该尽量不关心的实现细节。 compareTo 的文档指定您应该关心的只是符号:数字是负数(a.compareTo(b) < 0 意味着 a < b),零(a.compareTo(b) 意味着 a等于 b),或正数(a.compareTo(b) > 0 表示 a > b)。

在实践之前,我的建议是阅读文档。在这种情况下,Oracle参考资料清楚地解释了正数和负数的原因:

Compares two strings lexicographically. The comparison is based on the Unicode value of each character in the strings. The character sequence represented by this String object is compared lexicographically to the character sequence represented by the argument string. The result is a negative integer if this String object lexicographically precedes the argument string. The result is a positive integer if this String object lexicographically follows the argument string. The result is zero if the strings are equal; compareTo returns 0 exactly when the equals(Object) method would return true.

这里解释了为什么 -3 和 +5:

This is the definition of lexicographic ordering. If two strings are different, then either they have different characters at some index that is a valid index for both strings, or their lengths are different, or both. If they have different characters at one or more index positions, let k be the smallest such index; then the string whose character at position k has the smaller value, as determined by using the < operator, lexicographically precedes the other string. In this case, compareTo returns the difference of the two character values at position k in the two string -- that is, the value:

this.charAt(k)-anotherString.charAt(k)

If there is no index position at which they differ, then the shorter string lexicographically precedes the longer string. In this case, compareTo returns the difference of the lengths of the strings that is, the value:

this.length()-anotherString.length()

Java 字符串 class 提供了 .compareTo () 方法以按字典顺序比较字符串。

该方法的return是一个int,可以解释为:

  • returns < 0 然后调用该方法的 String 按字典顺序排在第一位(在字典中排在第一位)
  • returns == 0 那么这两个字符串在字典序上是等价的
  • returns > 0 那么传给compareTo方法的参数是字典序在前的

在你的例子中:

"axe".compareTo("dog") return -3 因为 axe 在词典中排在第一位。

它以每个字符串的第一个字符开始:a 在 dictionary.if 中的 d 之前比较的字符在字典顺序上是等效的 它将转到字符串中的下一个字符以进行比较等等。

 "applebee's".compareTo("apple") 

第一个字符串 "apple" 中的前 5 个字符在字典上等同于第二个字符串,但字符 bee's 出现在第二个字符串之后,因此它将 return 5 这是大于 0 因为第二个字符串在字典中排在第一位。