使用BigInteger覆盖public int hashCode()

问题描述:

BigInteter太大而无法转换为整数。但是我必须在HashMap中存储带有ID(SHA 512)的对象,并且需要一个没有多次冲突的散列函数。使用BigInteger覆盖public int hashCode()

我试过了。但是,我不确定是否没有集群。

@Override 
public boolean equals(Object obj) { 
    if (this == obj) { 
     return true; 
    } 
    if (obj == null) { 
     return false; 
    } 
    if (getClass() != obj.getClass()) { 
     return false; 
    } 
    Advertisement other = (Advertisement) obj; 
    return this.getId().equals(other.getId()); 
} 

@Override 
public int hashCode() { 
    return new BigInteger(getId(), 16).hashCode(); 
} 

会转换成整数(bi.intValue())更有效吗?

不要试图重新发明轮子 - 只需使用getId().hashCode()

@Override 
public int hashCode() { 
    return getId().hashCode(); 
} 


String.hashCode()使用高效,高品质的散列算法,所以这是最好的选择。它使你的代码更简单,这总是一件好事。

+0

thx我以为是这样 – headgrowe 2012-04-24 01:15:06