作者:双鱼天脎 | 来源:互联网 | 2023-05-18 14:11
IfyourunthefollowingonHotSpotJava764-bitversion.如果在HotSpotJava764位版本上运行以下命令。intcoun
If you run the following on HotSpot Java 7 64-bit version.
如果在HotSpot Java 7 64位版本上运行以下命令。
int countTopBit = 0, countLowestBit = 0;
for (int i = 0; i <100000000; i++) {
int h = new Object().hashCode();
if (h <0)
countTopBit++;
if ((h & 1) == 1)
countLowestBit++;
}
System.out.println("The count of negative hashCodes was " + countTopBit + ", the count of odd hashCodes was " + countLowestBit);
you can get a result like
你可以得到像这样的结果
The count of negative hashCodes was 0, the count of odd hashCodes was 49994232
I was wondering if this means the Object.hashCode()
is only really 31-bit and why this might be so?
我想知道这是否意味着Object.hashCode()只是31位,为什么会这样呢?
It is not the case that the top bit is not used. From the source for HashMap
不是不使用顶部位的情况。来自HashMap的源代码
257 /**
258 * Applies a supplemental hash function to a given hashCode, which
259 * defends against poor quality hash functions. This is critical
260 * because HashMap uses power-of-two length hash tables, that
261 * otherwise encounter collisions for hashCodes that do not differ
262 * in lower bits. Note: Null keys always map to hash 0, thus index 0.
263 */
264 static int hash(int h) {
265 // This function ensures that hashCodes that differ only by
266 // constant multiples at each bit position have a bounded
267 // number of collisions (approximately 8 at default load factor).
268 h ^= (h >>> 20) ^ (h >>> 12);
269 return h ^ (h >>> 7) ^ (h >>> 4);
270 }
1 个解决方案