【问题标题】:put method of HashmapHashmap的put方法
【发布时间】:2014-08-04 07:12:58
【问题描述】:

我看到在 HashMap 类的 put 方法的实现中,表桶是使用int i = indexFor(hash, table.length); 获得的,然后它向该桶添加一个条目 - 如果哈希码和键不相等,则为“i”。如果它们相等,则替换旧值。

  • 它如何使用密钥找到正确的存储桶?如果存储桶不存在怎么办?
  • 它如何评估是否需要将其添加到同一个桶或不同的桶中?
  • 当哈希码相同而键不同时会发生什么?如果哈希码相同,那么条目应该在同一个桶中,但我在 put 方法的代码中没有看到!

源代码:

public V put(K key, V value) {
    if (table == EMPTY_TABLE) {
        inflateTable(threshold);
    }
    if (key == null)
        return putForNullKey(value);
    int hash = hash(key);
    int i = indexFor(hash, table.length);
    for (Entry<K,V> e = table[i]; e != null; e = e.next) {
        Object k;
        if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
            V oldValue = e.value;
            e.value = value;
            e.recordAccess(this);
            return oldValue;
        }
    }

    modCount++;
    addEntry(hash, key, value, i);
    return null;
}


void addEntry(int hash, K key, V value, int bucketIndex) {
    if ((size >= threshold) && (null != table[bucketIndex])) {
        resize(2 * table.length);
        hash = (null != key) ? hash(key) : 0;
        bucketIndex = indexFor(hash, table.length);
    }

    createEntry(hash, key, value, bucketIndex);
}

void createEntry(int hash, K key, V value, int bucketIndex) {
        Entry<K,V> e = table[bucketIndex];
        table[bucketIndex] = new Entry<>(hash, key, value, e);
        size++;
    }

【问题讨论】:

  • 这里的问题太多了,一个问题。此外,通过阅读散列集合的一般工作原理可以很容易地回答这些问题。
  • 我在这篇文章中看到至少 4 个问题...
  • 要获得所有问题的答案,我认为最好查看`HashMap的源代码,
  • 例如,我使用了Google,然后我到达了,this article 回答了您的许多问题。 Google 是您的朋友。

标签: java collections hashmap


【解决方案1】:

前段时间出于练习目的,我写了哈希映射的简单实现(code),我认为阅读您的问题可以得到答案。

测试你可以找到here的实现

另一个使用列表的实现你可以找到here

【讨论】:

    【解决方案2】:

    indexOf() 方法的返回永远不会超过数组大小。 检查 HashTable 实现,它与 HashMap 不完全一样,但您会了解基本哈希的概念。

    假设你有 4 个 MyClass 对象。其哈希码值分别为 11、12、13、14。 并且您的默认哈希图大小为 10。 那么索引就是这样-

         index =   hashcode % table.length; 
                         1 =      11     %  10 ;
                         2 =      12     %  10 ;
                         3 =      13     %  10 ;
    

    1,2,3 是索引值,您的条目存储在数组中。

    如果你的类哈希码是 21,那么它的索引就是 21 % 10 = 1;

    索引 1 已经有一个 Entry 对象,所以它会被存储为 LinkedList。

    【讨论】:

      猜你喜欢
      • 2014-10-29
      • 2022-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-25
      • 2013-12-12
      • 2019-09-23
      • 2014-05-09
      相关资源
      最近更新 更多