String 类 compareTo() 方法返回什么 [英] What does the String classes compareTo() method return
问题描述
在 Oracle 的 Java API 中 website: "compareTo Returns: "如果参数字符串等于这个字符串,则值为 0;如果此字符串按字典顺序小于字符串参数,则为小于 0 的值;如果此字符串按字典顺序大于字符串参数,则为大于 0 的值." "
In the Java API on oracles website: "compareTo Returns: "the value 0 if the argument string is equal to this string; a value less than 0 if this string is lexicographically less than the string argument; and a value greater than 0 if this string is lexicographically greater than the string argument." "
这是一个 if 语句:
Here is an if statement:
String a = "abd";
String b = "abc";
if(a.compareTo(b) >= 1)
返回真因为字符串 a 更大,按字典顺序排列.
returns true since string a is greater, lexicographically.
我的问题是,compareTo 是否总是返回 0、1 或 -1?或者它是否返回字符串大于或小于字符串参数的实际数量.
My question is, does the compareTo always return a 0, 1, or -1? or does it return the actual amount that the string is greater than or less than the string argument.
那么在上面的 if 语句中,由于 "abd" 比 "abc" 大 1,所以它返回 1 吗?
So in the above if statement, since "abd" is one greater than "abc" is it returning 1?
推荐答案
就您而言,不知道 compareTo
返回值的大小是多少,只知道符号.在实践中,大多数 compareTo
实现将返回 -1、0 或 1,但契约明确规定了正数或负数,您应该相应地编写代码(例如,使用 int compare = a.compareTo(b); if(compare > 0) {...} else...
).
As far as you're concerned, there's no telling what the magnitude of the compareTo
return value is, just the sign. In practice, most compareTo
implementations will return -1, 0, or 1, but the contract specifically says positive or negative, and you should write your code accordingly (e.g., using int compare = a.compareTo(b); if(compare > 0) {...} else...
).
这篇关于String 类 compareTo() 方法返回什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!