JDK之String的equals和equalsIgnoreCase的实现
JDK8
这俩个方法经常用,今天突然好奇怎么实现的,之前也看过,不过今天再来看下,记录下来
equalsIgnoreCase
List-1
public boolean equalsIgnoreCase(String anotherString) { return (this == anotherString) ? true
: (anotherString != null)
&& (anotherString.value.length == value.length)
&& regionMatches(true, 0, anotherString, 0, value.length);
}
...
public boolean regionMatches(boolean ignoreCase, int toffset,
String other, int ooffset, int len) {
char ta[] = value;
int to = toffset;
char pa[] = other.value;
int po = ooffset;
// Note: toffset, ooffset, or len might be near -1>>>1.
if ((ooffset < 0) || (toffset < 0)
|| (toffset > (long)value.length - len)
|| (ooffset > (long)other.value.length - len)) {
return false;
}
while (len-- > 0) {
char c1 = ta[to++];
char c2 = pa[po++];
if (c1 == c2) {
continue;
}
if (ignoreCase) {
// If characters don"t match but case may be ignored,
// try converting both characters to uppercase.
// If the results match, then the comparison scan should
// continue.
char u1 = Character.toUpperCase(c1);
char u2 = Character.toUpperCase(c2);
if (u1 == u2) {
continue;
}
// Unfortunately, conversion to uppercase does not work properly
// for the Georgian alphabet, which has strange rules about case
// conversion. So we need to make one last check before
// exiting.
if (Character.toLowerCase(u1) == Character.toLowerCase(u2)) {
continue;
}
}
return false;
}
return true;
}
如List-1所示:
- 判断是否是本身
- 判断不为空,判断长度是否相等
- 在regionMatches方法中,俩个char[]从左边开始往右边逐个对比,如果直接比较俩个字符,不相等的话,将俩个字符先都转换为大写进行比较,如果大写不相等,那么再转换为小写——注释上写着格鲁吉亚的字符有问题
equals
List-2
public boolean equals(Object anObject) { if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String anotherString = (String)anObject;
int n = value.length;
if (n == anotherString.value.length) {
char v1[] = value;
char v2[] = anotherString.value;
int i = 0;
while (n-- != 0) {
if (v1[i] != v2[i])
return false;
i++;
}
return true;
}
}
return false;
}
- 判断是否是本身
- 判断长度,如果长度一样,那么逐个字符的比较
以上是 JDK之String的equals和equalsIgnoreCase的实现 的全部内容, 来源链接: utcz.com/z/518307.html