繁体   English   中英

Hashmap的put方法

[英]put method of Hashmap

我看到在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++;
    }

有时候,出于锻炼目的,我写了哈希图( 代码 )的简单实现,我认为阅读后可以得到有关您问题的答案。

测试该实现,您可以在这里找到

另一种利用列表的实现可以在这里找到

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。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM