compareTo如何工作? [英] How does compareTo work?
问题描述
我知道 compareTo
对于一个字符串与另一个字符串的相关程度返回否定或肯定的结果,但是为什么呢?
I know that compareTo
returns a negative or positive result on how well one string correlates to the other, but then why:
public class Test {
public static void main(String[] args) {
String y = "ab2";
if(y.compareTo("ac3") == -1) {
System.out.println("Test");
}
}
}
为真且
public class Test {
public static void main(String[] args) {
String y = "ab2";
if(y.compareTo("ab3") == -1) {
System.out.println("Test");
}
}
}
也是吗?
推荐答案
Comparable.compareTo(o)
是要返回的
The general contract of Comparable.compareTo(o)
is to return
- 如果大于另一个对象则为正整数。
- 如果小于另一个对象则为负整数
- 如果它等于另一个对象,则为0。
在您的示例中 ab2 .compareTo( ac3)== -1
和 ab2 .compareTo( ab3)== -1
仅表示,表示 ab2
低于两个 ac3
和 ab3
。仅通过以下示例,您无法得出关于 ac3
和 ab3
的任何内容。
In your example "ab2".compareTo("ac3") == -1
and "ab2".compareTo("ab3") == -1
only means that "ab2"
is lower than both "ac3"
and "ab3"
. You cannot conclude anything regarding "ac3"
and "ab3"
with only these examples.
由于 b
在字母表中的 c
之前(<$ c c $ c> ab2< ac3 )和 2
排在 3
(因此 ab2< ab3
):Java对字符串进行按字典顺序。
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.
这篇关于compareTo如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!