gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 04:40:52 25 4
gpt4 key购买 nike

我看到 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com