关于equals都会经常用到,但是compareTo可能不会经常使用,这里不对两种方法的功能做过多解释,度娘一下出来一堆,直接上源码
equals源码:
public boolean equals(Object anObject) {
if (this == anObject) {//这里提高效率
return true;
}
if (anObject instanceof String) {//这里提高效率
String anotherString = (String)anObject;
int n = count;
if (n == anotherString.count) {//这里提高效率
char v1[] = value;
char v2[] = anotherString.value;
int i = offset;
int j = anotherString.offset;
while (n-- != 0) {
if (v1[i++] != v2[j++])//关键这里
return false;
}
return true;
}
}
return false;
}
compareTo源码:
public int compareTo(String anotherString) {
int len1 = count;
int len2 = anotherString.count;
int n = Math.min(len1, len2);
char v1[] = value;
char v2[] = anotherString.value;
int i = offset;
int j = anotherString.offset;
if (i == j) {
int k = i;
int lim = n + i;
while (k < lim) {
char c1 = v1[k];
char c2 = v2[k];
if (c1 != c2) {//关键这里
return c1 - c2;
}
k++;
}
} else {
while (n-- != 0) {
char c1 = v1[i++];
char c2 = v2[j++];
if (c1 != c2) {//关键这里
return c1 - c2;
}
}
}
return len1 - len2;
}
在“关键这里”可以看到两个方法都是对ASCII码的比较,只不过返回值不同。
所以在面试的过程中可以说一下字符串比较的原理,再顺便把compareTo说一下