为什么有一个哈希码的转换来获得哈希,它是一个好主意的所有键? [英] Why is there a transformation of hashcode to get the hash and is it a good idea for all keys?

查看:238
本文介绍了为什么有一个哈希码的转换来获得哈希,它是一个好主意的所有键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到hashmap的实现应用某种转换到 hashCode 以获得实际的哈希。

可能有人请帮助

解决方案此外,如果这个转换工作 / div>

取自方法的Javadoc hash(Object) HashMap 实现(假设这是你关心的JVM):

 
/ **
* .hashCode()并将散列
*的较高位扩散(XOR)为较低。因为表使用了二次幂的掩蔽,
*哈希值的集合只有在当前掩码之上的位变化,
*总是会冲突。 (已知的示例是浮点键
*的集合,其在小表中保持连续的整数。)因此,我们
*应用向下扩展较高位
*的影响的变换。在速度,效用和
*位扩展质量之间存在权衡。因为许多常见的散列集合
*已经合理分布(因此不会受益于
*传播),并且因为我们使用树来处理大集合的b bb b *碰撞,只是XOR一些移位位在
*最便宜的可能的方式减少系统性损失,以及
*以包含最高位的影响,否则
*从不用于索引计算,因为的表边界。
* /
static final int hash(Object key){
int h;
return(key == null)? 0:(h = key.hashCode())^(h >>> 16);
}


I see that the implementation of the hashmap applies some kind of transformation to the hashCode to get the actual hash.
Could some one please help me understand how this transformation works and additionally if it would make any difference if the object to store is just an integer?

解决方案

As taken from the Javadoc of the method hash(Object) in the OpenJDK Java 8 HashMap implementation (assuming this is the JVM you are concerned about):

/**
 * 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);
}

这篇关于为什么有一个哈希码的转换来获得哈希,它是一个好主意的所有键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆