java - 为什么需要对哈希码进行转换来获取哈希值,这对于所有键来说都是一个好主意吗?

标签 java data-structures collections hashmap

我看到 HashMap 的实现对hashCode应用了某种转换。获取实际的哈希值。
有人可以帮助我理解这种转换是如何工作的吗?另外,如果要存储的对象只是一个整数,它是否会产生任何影响?

最佳答案

取自方法的 Javadoc hash(Object)在 OpenJDK Java 8 HashMap 实现中(假设这是您关心的 JVM):

/**
 * Computes key.hashCode() and spreads (XORs) higher bits of hash
 * to lower.  Because the table uses power-of-two masking, sets of
 * hashes that vary only in bits above the current mask will
 * always collide. (Among known examples are sets of Float keys
 * holding consecutive whole numbers in small tables.)  So we
 * apply a transform that spreads the impact of higher bits
 * downward. There is a tradeoff between speed, utility, and
 * quality of bit-spreading. Because many common sets of hashes
 * are already reasonably distributed (so don't benefit from
 * spreading), and because we use trees to handle large sets of
 * collisions in bins, we just XOR some shifted bits in the
 * cheapest possible way to reduce systematic lossage, as well as
 * to incorporate impact of the highest bits that would otherwise
 * never be used in index calculations because of table bounds.
 */
static final int hash(Object key) {
    int h;
    return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}

关于java - 为什么需要对哈希码进行转换来获取哈希值,这对于所有键来说都是一个好主意吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30225054/

相关文章:

c - 移动指针后的 Malloc 在 C 中不起作用?

java - 线程安全的 CopyOnWriteArrayList 反向迭代

c# - 展开集合并保存一些字段。

java - 如何基于堆栈等自定义数据结构创建 ObservableList

java - PriorityQueue 适合这种情况吗?

java - 如何让字符串显示在 jLabel 中?

java - @JsonbTypeDeserializer 和 @JsonbTypeSerializer 在字段中不起作用

java - ActiveMQ分布式事务+扩展

java - 正则表达式查找方法调用

java - 为什么这个 while 循环陷入无限循环?