我阅读了说明,但是我无法理解通过对hashCode进行XOR所实现的目标。谁能举个例子。
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
此代码摘自HashMap源代码。我只是想知道为什么他们使用XOR,Marko正确地回答说HashMap实现使用低端位。我认为不仅HashMap,其他集合也将这样做,这就是为什么我没有提到任何集合名称的原因。我不明白为什么人们会“贬低”这个问题。
这是一种防止“错误”哈希码的典型方法:此类低端位的变量不够可变。 Java的HashMap
实现仅依赖哈希码的低端位来选择存储桶。
但是,此代码的动机已经很久了,因为HashMap
已经进行了自己的扩展。如果在Hashtable
上使用它会很有意义,但是当然,自2000年以来编写的任何代码都不应使用它。
该代码是openjdk java HashMap源代码:HashMap.java
/**
* 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);
}
xor是为了让散列结果更加分散