为什么 String 中的 equals 方法不使用哈希?
类 String 中该方法的代码为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;
}
我有一个问题 - 为什么这种方法不使用hashCode()?
据我所知,hashCode()可以快速比较两个字符串。
更新:我知道,两个不相等的字符串可以具有相同的哈希值。但两个相等的字符串具有相等的哈希值。因此,通过使用hashCode(),我们可以立即看到两个字符串是不相等的。
我只是认为使用hashCode()可以是一个很好的过滤器。equals
更新2:这里有一些代码,关于我们在这里谈论的。
这是一个字符串方法等于如何看起来像这样的例子
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String anotherString = (String)anObject;
if (hashCode() == anotherString.hashCode()){
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;
}
}else{
return false;
}
}
return false;
}