有大量长字符串需要比较,JDK提供的equals()方法实在太慢
想利用 String类的 hashCode() 方法相等来比较,但对于不同的长字符串来说 hashCode()重复的几率挺高
于是有个想法:
如果两个String 的 length()和hashCode()都相等,是否一定 equals()成立呢?(没有反向推的要求)
这个设想还未得到理论证明,请大家给点意见,谢谢!
想利用 String类的 hashCode() 方法相等来比较,但对于不同的长字符串来说 hashCode()重复的几率挺高
于是有个想法:
如果两个String 的 length()和hashCode()都相等,是否一定 equals()成立呢?(没有反向推的要求)
这个设想还未得到理论证明,请大家给点意见,谢谢!
-------------------------------------
public int hashCode() {
int h = hash;
if (h == 0) {
int off = offset;
char val[] = value;
int len = count; for (int i = 0; i < len; i++) {
h = 31*h + val[off++];
}
hash = h;
}
return h;
}
-----------------------------------------
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;
}
最好还是自己写个算法。
>>如果两个String 的 length()和hashCode()都相等,是否一定 equals()成立呢?(没有反向推的要求)不一定. 但是这个概率应该比较低. 看看你的业务能否允许这个概率了.另外,求hashCode() 的jdk 代码:
public int hashCode() {
int h = hash;
if (h == 0) {
int off = offset;
char val[] = value;
int len = count; for (int i = 0; i < len; i++) {
h = 31*h + val[off++];
}
hash = h;
}
return h;
}如果你每个字符串只比较一次的话,那么hashCode() 不会比equals 快的.
所以 hashCode 是肯定有重复的,这点已经得到了证明,所以才想办法退而求其次PS:比较引用……肯定不成的哦。
就用多线程搞就得了贝
用的着那么抠,都抠到hashCode() 是不是真的比 equals() 快吗?十几万次,几十万次,
仅仅是因这两个方法产生的时间差距可以忽略不计了
不如把时间和精力花在优化其他方面上
另外,是不是快,我想,看源代码的长度是没用的
受其启发,不知是否可以先比较字符串的长度,不同再继续比较第一个字母,不同再继续下去,hashCode(),equals()。