HashMap在内部使用LinkedList [英] HashMap uses LinkedList internally

查看:96
本文介绍了HashMap在内部使用LinkedList的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  public V get(Object key){
if(key == null)
return getForNullKey();
int hash = hash(key.hashCode());
for(Entry< K,V> e = table [indexFor(hash,table.length)];
e!= null;
e = e.next){
Object k ;
if(e.hash == hash&&((k = e.key)== key || key.equals(k)))
return e.value;
}
返回null;
}

我知道的是,如果你想从 HashMap ,首先它会根据散列码/散列值搜索散列桶,然后遍历该散列桶中的 LinkedList (假设diff对象具有相同的散列码,因此在同一个散列桶中)。

但是在查看上面的代码之后,我无法理解它何时迭代LinekedList(其中是LinkedList)

解决方案

存储区 是链接列表。 数组是一个 Entry 元素的数组,并且每个 Entry 是一个链表,因为每个条目都知道列表中的下一个条目,直到下一个引用为空为止。 $ for 循环显示了对链表的迭代。



这不是 LinkedList 就像 java.util.LinkedList - 它是一个单独的(更简单)的实现,仅用于地图。


public V get(Object key) {
if (key == null)
    return getForNullKey();
    int hash = hash(key.hashCode());
    for (Entry<K,V> e = table[indexFor(hash, table.length)];
         e != null;
         e = e.next) {
        Object k;
        if (e.hash == hash && ((k = e.key) == key || key.equals(k)))
            return e.value;
    }
    return null;
}

What I knew is, if you want to get a object from HashMap, first of all it searches the hash bucket based on hashcode/hash value and then iterates through the LinkedList in that hashbucket(suppose the diff objects have same hash code, thus in the same hash bucket).

But after looking at the code above, I am not able to understand when it iterates through the LinekedList(and where is the LinkedList)

解决方案

The bucket is the linked list, effectively. The table array is an array of Entry elements, and each Entry is a linked list, in that each entry knows about the next one in the list, until you reach the end when the next reference is null. The for loop you've shown iterates over the linked list.

It's not a LinkedList as in a java.util.LinkedList - it's a separate (simpler) implementation just for the map.

这篇关于HashMap在内部使用LinkedList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆