Mar*_*llo 44 java string hashcode
equals
String类中方法的代码是
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;
}
Run Code Online (Sandbox Code Playgroud)
我有一个问题 - 为什么这个方法不使用hashCode()?
据我所知,hashCode()可以快速比较两个字符串.
更新:我知道,两个不相等的字符串,可以有相同的哈希值.但两个相等的字符串具有相等的哈希值.因此,通过使用hashCode(),我们可以立即看到两个字符串是不相等的.
我只是想,使用hashCode()方法可以很好的过滤器在equals
.
更新2:这里有一些代码,我们在这里谈论.
这是String方法等于的示例
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;
}
Run Code Online (Sandbox Code Playgroud)
par*_*fal 39
Hashcode可能是对不平等的第一轮检查.但是,它提出了一些权衡.
String
哈希码是懒惰计算的,尽管它们使用"保护"值.如果你要比较长寿命的字符串(即,他们可能已经计算了哈希码),这不是问题.否则,您将无法计算哈希码(可能很昂贵)或者在尚未计算哈希码时忽略检查.如果你有很多短命的字符串,你会比你使用它更频繁地忽略支票.ass*_*ias 14
这个问题实际上已经被JDK的开发人员考虑过了.我在各种消息中找不到为什么它没有被包括在内.增强功能也列在错误数据库中.
即,建议的变更之一是:
public boolean equals(Object anObject) {
if (this == anObject) // 1st check identitiy
return true;
if (anObject instanceof String) { // 2nd check type
String anotherString = (String)anObject;
int n = count;
if (n == anotherString.count) { // 3rd check lengths
if (n != 0) { // 4th avoid loading registers from members if length == 0
int h1 = hash, h2 = anotherString.hash;
if (h1 != 0 && h2 != 0 && h1 != h2) // 5th check the hashes
return false;
Run Code Online (Sandbox Code Playgroud)
还有一个讨论==
用于实习字符串(即两个字符串是否被实习:) if (this != anotherString) return false;
.
归档时间: |
|
查看次数: |
4633 次 |
最近记录: |