简体   繁体   English

compareTo() 实际上返回什么?

[英]What does compareTo() actually return?

The compareTo() method in Java returns a value greater/equal/less than 0 and i know that. Java 中的compareTo()方法返回一个大于/等于/小于 0 的值,我知道这一点。 However, the value itself is my question.但是,价值本身是我的问题。 What is the difference between 2 or 4 when compareTo() returns. compareTo()返回时 2 或 4 之间有什么区别。 Look at the code below看下面的代码

String s1="hello";  
String s2="hello";  
String s3="meklo";  
String s4="hemlo";  
System.out.println(s1.compareTo(s2));     // 0
System.out.println(s1.compareTo(s3));     // -5
System.out.println(s1.compareTo(s4));     // -1

Why the last two commands are -5 and -1?为什么最后两个命令是 -5 和 -1?

https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#compareTo(java.lang.String) https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#compareTo(java.lang.String)

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;如果它们在一个或多个索引位置有不同的字符,则令 k 为最小的此类索引; then the string whose character at position k has the smaller value, as determined by using the < operator, lexicographically precedes the other string.则在位置 k 处的字符具有较小值的字符串(通过使用 < 运算符确定)按字典顺序排在另一个字符串之前。 In this case, compareTo returns the difference of the two character values at position k in the two string -- that is, the value:在这种情况下, compareTo 返回两个字符串中位置 k 处的两个字符值的差——即值:

this.charAt(k)-anotherString.charAt(k) 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:在这种情况下, compareTo 返回字符串长度的差值——即值:

this.length()-anotherString.length() this.length()-anotherString.length()

compareTo() returns the difference of first unmatched character in the two compared strings. compareTo()返回两个比较字符串中第一个不匹配字符的差异。 If no unmatch is found, and one string comes out as shorter than other one, then the length difference is returned.如果没有找到不匹配,并且一个字符串比另一个字符串短,则返回长度差异

"hello".compareTo("meklo") = 'h' - 'm'  = -5
 ^                 ^
and 

"hello".compareTo("hemlo") = 'l' - 'm'  = -1
   ^                 ^

As a side note: Non-zero values are mostly considered as true inside conditional statements.作为旁注:非零值在条件语句中通常被认为是true So, compareTo can simply return these non-zero values instead of processing them into 1 ( small optimisation ).因此, compareTo可以简单地返回这些非零值,而不是将它们处理为1小优化)。

If you take closer look at the source code for String#compareTo(String) , you can see that the exact results are ambiguous.如果您仔细查看String#compareTo(String)的源代码,您会发现确切的结果是不明确的。

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 (ie a difference in the characters of both strings) it will return the integer difference of the char values of the first differing characters.在大多数情况下(即两个字符串的字符不同),它将返回第一个不同字符的 char 值的整数差异。 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<T>#compareTo(T) is kept:返回值超出= 0 , > 0< 0的解释在实践中应该是Comparable<T>#compareTo(T) ,因为如果Comparable<T>#compareTo(T)被保留,则实现可以随时更改:

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-来源: https : //docs.oracle.com/javase/8/docs/api/java/lang/Comparable.html#compareTo-T-

The exact value does not matter - all that the Comparable (as well as Comparator ) interface cares about is whether the value is negative, zero or positive.确切的值并不重要 - Comparable (以及Comparator )接口关心的只是该值是负数、零还是正数。

This is to make things simple for implementations of the interface.这是为了使接口的实现变得简单。 When implementing it, you may choose to return the basic -1, 0 or 1 (this is usual if the comparison relies on evaluating some conditions), or you may use any arbitrary negative or positive value if it suits you better - eg you can compare two integers by returning this.i - other.i .在实现它时,您可以选择返回基本的 -1、0 或 1(如果比较依赖于评估某些条件,这很常见),或者您可以使用任何更适合您的任意负值或正值 - 例如,您可以通过返回this.i - other.i比较两个整数。


In your particular given example, my guess would be:在您给出的特定示例中,我的猜测是:

  • -1 is difference in the third letter's code point: 'l' - 'm' == -1 -1是第三个字母的代码点不同: 'l' - 'm' == -1
  • -5 is difference in the first letter's code point: 'h' - 'm' == -5 -5是第一个字母的代码点不同: 'h' - 'm' == -5

But the important part is that you shall not rely on it to be that way - it's an implementation detail, and according to Comparable 's contract any negative value shall be treated the same ("less than").但重要的部分是你不能依赖它——这是一个实现细节,根据Comparable的合同,任何负值都应被视为相同(“小于”)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM