【问题标题】:How can Java's String.hashCode() function be used to make hash tables?如何使用 Java 的 String.hashCode() 函数制作哈希表?
【发布时间】:2015-10-30 06:02:26
【问题描述】:

刚开始在我的一堂课上学习哈希表。我的理解是,它们的工作方式是表中元素的索引应该用哈希函数来确定。我正在尝试为大量字符串创建一个哈希表,我们的讲师鼓励我们使用 Java 的字符串方法hashCode()。假设我想将所有这些字符串放在一个数组中,words[]

这是我不明白的。我该怎么处理这个号码?生成的哈希似乎很大。 “堆栈”的哈希码是 109757064,“溢出”的哈希码是 529642498。相差超过 4 亿,这将是一个非常荒谬的大表,更不用说有多少索引没有分配给他们的字符串.所以我可以有words[109757064] = "stack"words[529642498] = "overflow",但这显然很荒谬。

我在这里缺少什么?在获取哈希码和在我的数组中为其分配索引之间是否有一个步骤?

【问题讨论】:

    标签: java string hash


    【解决方案1】:

    是的,有。

    您从那个巨大的哈希码开始,然后再次对其进行哈希处理以匹配您拥有的存储桶数量。

    可以是简单的code % buckets

    java.util.HashMap 使用的 real-life implementation 本质上就是 (code & (buckets - 1)),但他们首先应用了另一个哈希函数来防止一些麻烦的边缘情况。

      257       /**
      258        * Applies a supplemental hash function to a given hashCode, which
      259        * defends against poor quality hash functions.  This is critical
      260        * because HashMap uses power-of-two length hash tables, that
      261        * otherwise encounter collisions for hashCodes that do not differ
      262        * in lower bits. Note: Null keys always map to hash 0, thus index 0.
      263        */
      264       static int hash(int h) {
      265           // This function ensures that hashCodes that differ only by
      266           // constant multiples at each bit position have a bounded
      267           // number of collisions (approximately 8 at default load factor).
      268           h ^= (h >>> 20) ^ (h >>> 12);
      269           return h ^ (h >>> 7) ^ (h >>> 4);
      270       }
      271   
      272       /**
      273        * Returns index for hash code h.
      274        */
      275       static int indexFor(int h, int length) {
      276           return h & (length-1);
      277       }
    

    【讨论】:

    • 感谢您的回复。抱歉,这是一个愚蠢的问题,但在这种情况下,“桶”是什么意思?
    • 你的数组在哈希表中的元素个数。
    猜你喜欢
    • 2014-02-01
    • 1970-01-01
    • 2010-09-30
    • 1970-01-01
    • 2011-07-14
    • 1970-01-01
    • 2016-03-25
    • 2011-02-27
    • 2014-04-18
    相关资源
    最近更新 更多