包含不同但相似字符串的对象的Java哈希码()冲突

在验证程序的输出数据时,我确定了两个不同对象的哈希码相同的情况.为了获得这些代码,我使用了以下函数:

int getHash( long lID, String sCI, String sCO, double dSR, double dGR, String sSearchDate ) {

    int result = 17;
    result = 31 * result + (int) (lID ^ (lID >>> 32));
    long temp;
    temp = Double.doubleToLongBits(dGR);
    result = 31 * result + (int) (temp ^ (temp >>> 32));
    temp = Double.doubleToLongBits(dSR);
    result = 31 * result + (int) (temp ^ (temp >>> 32));
    result = 31 * result + (sCI != null ? sCI.hashCode() : 0);
    result = 31 * result + (sCO != null ? sCO.hashCode() : 0);
    result = 31 * result + (sSearchDate != null ? sSearchDate.hashCode() : 0);

    return result;
}

这是两个示例案例:

getHash( 50122,"03/25/2015","03/26/2015",4.0,8.0,"03/24/15 06:01" )
getHash( 51114,"03/24/2015","03/25/2015",4.0,8.0,"03/24/15 06:01" )

我想,这个问题出现了,因为我的数据中存在三个非常相似的字符串,字符串A到B和B到C之间的哈希码的差异大小相同,导致返回的哈希码相同.

IntelliJ提出的hashcode()实现使用31作为每个变量的乘数,这些变量有助于最终的哈希码.我想知道为什么一个人没有为每个变量使用不同的值(比如33,37,41(我在其他帖子中提到过处理哈希码时已提到))?在我的情况下,这将导致我的两个对象之间的区别.

但我想知道这是否会导致其他情况下的问题?

有关于此的任何想法或提示吗?非常感谢你!

解决方法:

hashCode()契约允许不同的对象具有相同的哈希码.从documentation

It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hash tables.

但是,既然你的哈希有一堆参数,你可以考虑使用Objects.hash()而不是自己的实现:

@Override
int getHash(long lID, String sCI, String sCO, double dSR, double dGR, String sSearchDate) {
    return Objects.hash(lID, sCI, sCO, dSR, dGR, sSearchDate);
}

例如:

Objects.hash(50122, "03/25/2015", "03/26/2015", 4.0, 8.0, "03/24/15 06:01")
Objects.hash(51114, "03/24/2015", "03/25/2015", 4.0, 8.0, "03/24/15 06:01")

结果是:

-733895022
-394580334
上一篇:python – pygame精灵墙碰撞


下一篇:E: Sub-process /usr/bin/dpkg returned an error code (1) 解决方案