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(),我们可以立即看到两个字符串不相等。
我只是想在 equals
中使用 hashCode() 可以是一个很好的 filter。
更新 2:这里有一些代码,关于我们在这里讨论。
这是一个字符串方法equals的例子
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;
}
最佳答案
哈希码可以作为不等式的第一轮检查。但是,它带来了一些折衷。
String
哈希码是惰性计算的,尽管它们确实使用了“保护”值。如果您正在比较具有长生命周期的字符串(即,它们可能已经计算了哈希码),这不是问题。否则,您要么计算哈希码(可能很昂贵),要么在尚未计算哈希码时忽略检查。如果您有很多短命字符串,那么您忽略检查的次数会多于使用检查的次数。- 在现实世界中,大多数字符串的前几个字符不同,因此首先检查哈希码不会节省太多。当然,也有异常(exception)(例如 URL),但同样,在现实世界编程中它们很少发生。
关于java - 为什么String中的equals方法不使用hash?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14262431/