当前位置: 代码迷 >> J2SE >> 关于java取hash值的有关问题
  详细解决方案

关于java取hash值的有关问题

热度:11   发布时间:2016-04-23 19:37:22.0
关于java取hash值的问题
static int hash(int h) {
        // This function ensures that hashCodes that differ only by
        // constant multiples at each bit position have a bounded
        // number of collisions (approximately 8 at default load factor).
        h ^= (h >>> 20) ^ (h >>> 12);
        return h ^ (h >>> 7) ^ (h >>> 4);
    }
这个是他的HASH算法,通过这个把这个KV放到数组下,然后,在他取值的时候,他会调用INDEXFOR方法
 static int indexFor(int h, int length) {
        return h & (length-1);
    }
。我想问的是,为什么以上两端代码要这样写?
------解决思路----------------------
引用:
Quote: 引用:

1. 为了尽可能散列
2. length-1处截断
为什么第一段代码就可以尽可能散列,有什么数学公式吗?

单独研究这个
h ^= (h >>> 20) ^ (h >>> 12);
通过位移之后,数值已经均匀分布到不同位段之上,再异或,结果就会尽可能不同
  相关解决方案