1、字符串比较
(1)逐个字符依次比较,当前位置字符不同时,直接返回ASCII码差值;
(2)两个字符串前 lim (limt = min(len1, len2)) 个字符相等时,返回两个字符串长度的差值;
下面是String类封装的方法:
/*
* @param anotherString the {@code String} to be compared.
* @return the value {@code 0} if the argument string is equal to
* this string; a value less than {@code 0} if this string
* is lexicographically less than the string argument; and a
* value greater than {@code 0} if this string is
* lexicographically greater than the string argument.
*/
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;
}
2、Integer、Float、Double、BigDecimal比较
a.compareTo(b)
(1)a > b 返回1;
(2)a < b 返回-1;
(3)a=b返回0;