【问题标题】:hashcode impementation in hashmaphashmap中的hashcode实现
【发布时间】:2017-03-30 11:04:50
【问题描述】:

我正在完成 Hashmap 的实现,并在下面找到了计算哈希码的代码。能否请您解释一下下面如何计算 h 的值以及为什么以这种特定方式完成?

final int hash(Object k) {
    int h = hashSeed;
    if (0 != h && k instanceof String) {
        return sun.misc.Hashing.stringHash32((String) k);
    }

    h ^= k.hashCode();

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

【问题讨论】:

    标签: java hash hashmap


    【解决方案1】:

    Hashcode 是使用hashCode() 函数计算得出的。您必须先查看该功能。

    计算哈希码后再次使用下面的重新哈希的原因

    h ^= (h >>> 20) ^ (h >>> 12);
    return h ^ (h >>> 7) ^ (h >>> 4);
    

    是为了避免进一步的碰撞。

    找到原作

     /**
     * Applies a supplemental hash function to a given hashCode, which
     * defends against poor quality hash functions.  This is critical
     * because HashMap uses power-of-two length hash tables, that
     * otherwise encounter collisions for hashCodes that do not differ
     * in lower bits. Note: Null keys always map to hash 0, thus index 0.
     */
    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);
    }
    

    查看 cmets。

    【讨论】:

      【解决方案2】:

      这是一种确保每个对象的哈希码唯一的方法,创建种子进行一些操作以找到唯一的键,并且该键将存储在映射中。

      如您所知,Map 将信息存储为键值对。那么该方法最重要的一行是

      h ^= k.hashCode();
      

      您需要确保在您的代码中,如果决定重写 hashCode() 方法,即按对象返回唯一的代码/ID,或者您可以在同一个映射中重写不同的对象。

      我希望这能澄清你的疑惑

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-12-12
        • 1970-01-01
        • 1970-01-01
        • 2019-12-02
        • 2018-06-27
        • 1970-01-01
        • 2010-11-07
        • 2012-04-16
        相关资源
        最近更新 更多