我对 HashSet 的内部工作有点困惑,因为我知道 HashSet 使用 key(K) 来找到正确的桶并使用 equals 来比较值,但是 HashSet 的工作方式意味着它如何生成哈希键?
最佳答案
在这里
final int hash(Object k) {
int h = hashSeed;
if (0 != h && k instanceof String) {
return sun.misc.Hashing.stringHash32((String) k);
}
h ^= k.hashCode();
// This function ensures that hashCodes that differ only by
// constant multiples at each bit position have a bounded
// number of collisions (approximately 8 at default load factor).
h ^= (h >>> 20) ^ (h >>> 12);
return h ^ (h >>> 7) ^ (h >>> 4);
}
其实是在HashSet内部使用的HashMap中
关于java - HashSet 如何为对象或值创建 hashkey,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21570049/