当我们使用compareTo()方法比较java中的字符串时,它实际比较的是,它是比较字符串的长度还是比较它的内容?
答案 0 :(得分:1)
此方法有两种变体。第一种方法将此String与另一个Object进行比较,第二种方法按字典顺序比较两个字符串。
语法: 以下是此方法的语法:
int compareTo(Object o)
or
int compareTo(String anotherString)
参数:
以下是参数的详细信息:
o -- the Object to be compared.
anotherString -- the String to be compared.
返回值:
如果参数是一个按字典顺序排列等于该字符串的字符串,则值为0;如果参数是按字典顺序大于此字符串的字符串,则小于0的值;如果参数是一个按字典顺序小于该字符串的字符串,则值大于0。
例如:
public class Test {
public static void main(String args[]) {
String str1 = "Strings are immutable";
String str2 = "Strings are immutable";
String str3 = "Integers are not immutable";
int result = str1.compareTo( str2 );
System.out.println(result);
result = str2.compareTo( str3 );
System.out.println(result);
result = str3.compareTo( str1 );
System.out.println(result);
}
}
结果: 这会产生以下结果:
0
10
-10
答案 1 :(得分:0)
检查 dictionary order
int compareTo(String str)
这里,str是与调用String进行比较的String。返回比较结果并解释如下:
Value Meaning
Less than zero The invoking string is less than str.
Greater than zero The invoking string is greater than str.
Zero The two strings are equal.