我将大量对象(具有存储在对象的字节数组中的唯一值组合)存储在哈希映射(约 280 万个对象)中,并且在检查我是否有任何哈希码冲突(32 位哈希),我很惊讶地发现没有,而在统计上,我有几乎 100% 的机会发生至少一次碰撞(参见http://preshing.com/20110504/hash-collision-probabilities/)。
因此,我想知道我检测碰撞的方法是否有问题,或者我是否非常幸运......
以下是我尝试从存储在地图中的 280 万个值中检测碰撞的方法:
HashMap<ShowdownFreqKeysVO, Double> values;
(...fill with 2.8 mlns unique values...)
HashSet<Integer> hashes = new HashSet<>();
for (ShowdownFreqKeysVO key:values.keySet()){
if (hashes.contains(key.hashCode())) throw new RuntimeException("Duplicate hash for:"+key);
hashes.add(key.hashCode());
}
这是对象创建哈希值的方法:
public class ShowdownFreqKeysVO {
//Values for the different parameters
public byte[] values = new byte[12];
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + Arrays.hashCode(values);
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ShowdownFreqKeysVO other = (ShowdownFreqKeysVO) obj;
if (!Arrays.equals(values, other.values))
return false;
return true;
}
}
任何关于我做错了什么的想法/提示将不胜感激!
谢谢,托马斯