java compareTo 是如何工作的?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32443402/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How does compareTo work?
提问by Harsh
I know that compareTo
returns a negative or positive result on how well one string correlates to the other, but then why:
我知道这会compareTo
返回关于一个字符串与另一个字符串的关联程度的负面或正面结果,但为什么:
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?
也是真的吗?
回答by Tunaki
The general contract of Comparable.compareTo(o)
is to return
一般合同Comparable.compareTo(o)
是退货
- 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.
- 如果这大于另一个对象,则为正整数。
- 如果这低于另一个对象,则为负整数。
- 如果这等于另一个对象,则为 0。
In your example "ab2".compareTo("ac3") == -1
and "ab2".compareTo("ab3") == -1
only meansthat "ab2"
is lower than both "ac3"
and "ab3"
. You cannot conclude anything regarding "ac3"
and "ab3"
with only these examples.
在你的榜样"ab2".compareTo("ac3") == -1
和"ab2".compareTo("ab3") == -1
唯一的手段是"ab2"
比两个下"ac3"
和"ab3"
。你不能断定任何方面"ac3"
和"ab3"
只有这些例子。
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.
这个结果是预期的,因为在字母表中b
出现在之前c
(so "ab2" < "ac3"
) 和2
出现在3
(so "ab2" < "ab3"
)之前:Java 按字典顺序对字符串进行排序。
回答by Eran
compareTo
for String
s 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.
compareTo
String
如果第一个String
(调用String
方法的那个)按字典顺序排在第二个(方法的参数)之前,则for s 返回 -1 。"ab2" 出现在 "ab3" 之前(因为前两个字符相等并且 2 在 3 之前)并且也在 "ac3" 之前(因为第一个字符相等并且 b 在 c 之前),所以两个比较都返回 -1。
回答by alcfeoh
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:
compareTo() 根据字母顺序比较两个字符串。您的两个测试都有一个字符串,该字符串在您与之比较的字符串“之前”按字母顺序排序。换句话说:
- ab2 < ac3 (because b < c)
- ab2 < ab3 (because 2 < 3)
- ab2 < ac3(因为 b < c)
- ab2 < ab3(因为 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"
顺便说一句,您应该在 if 语句中使用“< 0”而不是“== -1”,因为compareTo
规范说该函数返回一个负数,而不是专门的“-1”