Java 中的 compareTo() 函数

compareTo() function in Java

我写了下面的代码

import java.util.*;
class compare{
    public static void main(String []args){
        String s1="java";
        String s2="javaProgramming";
        System.out.println(s1.compareTo(s2));
    }
}

这段代码的输出是-11。由于java中没有字符串终止字符,"java"中的哪个字符与"javaProgramming"中的'P'进行比较?

'P' 字符未与第一个 String 中的任何内容进行比较。

只比较2个String的前4个字符,它们是相等的

然后returns第一个字符串的长度减去第二个字符串的长度。

public int compareTo(String anotherString) {
    int len1 = value.length;
    int len2 = anotherString.value.length;
    int lim = Math.min(len1, len2);
    char v1[] = value;
    char v2[] = anotherString.value;

    int k = 0;
    while (k < lim) {
        char c1 = v1[k];
        char c2 = v2[k];
        if (c1 != c2) {
            return c1 - c2;
        }
        k++;
    }
    return len1 - len2;
}

由于第二个 String 较长,而第一个 String 包含在第二个中,因此返回任何负值都可以,因为较短的 String 应该在字典序中排在第一位订单。

the source code可以看出,当达到每个字符串的最小长度时,比较停止。如果通过该点所有字符都相等,则返回长度差。

看看javadocs怎么说

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.

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()