What does compareTo() actually return?

后端 未结 4 1826
感动是毒
感动是毒 2021-01-20 16:53

The compareTo() method in Java returns a value greater/equal/less than 0 and i know that. However, the value itself is my question. What is the difference betwe

4条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-20 16:56

    If you take closer look at the source code for String#compareTo(String), you can see that the exact results are ambiguous.

    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;
    }
    

    In most cases (i.e. a difference in the characters of both strings) it will return the integer difference of the char values of the first differing characters. Otherwise it will return the difference of the lengths of both strings.

    The interpretation of the return value beyond = 0, > 0 and < 0 should be of no concern in practice, since the implementation is allowed to change at any time if the contract of Comparable#compareTo(T) is kept:

    Compares this object with the specified object for order. Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.

    Source: https://docs.oracle.com/javase/8/docs/api/java/lang/Comparable.html#compareTo-T-

提交回复
热议问题