Why is there a transformation of hashcode to get the hash and is it a good idea for all keys? [duplicate]

允我心安 提交于 2019-12-12 03:01:27

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/30225054/why-is-there-a-transformation-of-hashcode-to-get-the-hash-and-is-it-a-good-idea

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!