这是什么意思?Entry<K,V> e = table[bucketIndex];

huangapple go评论138阅读模式
英文:

What does this mean? Entry<K,V> e = table[bucketIndex];

问题

我正在研究HashMap内部的工作原理,但无法理解这个方法:

void addEntry(int hash, K key, V value, int bucketIndex) {
    Entry<K,V> e = table[bucketIndex];
    table[bucketIndex] = new Entry<K,V>(hash, key, value, e);
    if (size++ >= threshold)
        resize(2 * table.length);
}

为什么对象**e**获得了table[bucketIndex]的地址(或者这里发生了什么?),然后table[bucketIndex]得到了新的<code>Entry<K,V>(hash, key, value, e)。为什么不直接使用下面的内容呢?

Entry<K,V> e = new Entry<K,V>(hash, key, value)
table[bucketIndex] = e;
英文:

I am studying how HashMap works inside and can not understand this method:

> void addEntry(int hash, K key, V value, int bucketIndex) {
> Entry<K,V> e = table[bucketIndex];
> table[bucketIndex] = new Entry<K,V>(hash, key, value, e);
> if (size++ >= threshold)
> resize(2 * table.length);

Why object e gets the address (or what happens here?) of table[bucketIndex] and then this table[bucketIndex] get the new <code>Entry<K,V>(hash, key, value, e)</code>? What is the reason, why didn't just use what is below?

Entry&lt;K,V&gt; e = new Entry&lt;K,V&gt;(hash, key, value)
table[bucketIndex] = e;

答案1

得分: 2

因为在HashMap中可能会发生冲突(即产生相同的bucketIndex的不同键)。如果按照你提出的建议去做,那么在发生冲突的情况下,最后插入的元素将以一种几乎不可预测的方式删除先前的元素。

Entry被实现为一种链表,因此它实际上被命名得有些不准确,实际上它是条目链表的一个节点。这就是为什么在Entry构造函数中将e作为最后一个参数传递的原因。

创建一个引用先前条目(e)的新Entry,并将其添加到与e相同的位置,就是在链表开头插入新节点的操作,即使enull(即根本没有发生冲突,而创建的Entry是具有给定bucketIndex的第一个条目)。

英文:

Because there could be collisions in the HashMap (i.e. different keys which produces the same bucketIndex). If they did what you suggests, in the case of a collision, the last inserted element would delete the previous ones in the case of a collision, possibly in a virtually unpredictable manner.

The Entry is implemented as some sort of linked list, so it is actually a bit misnamed and is in fact a node of linked list of entries. This is the reason why e is passed as the last parameter of Entry constructor.

Creating a new Entry that refers to the previous one (the e) and adding it in the same place where the e was is the operation of inserting a new node in the beggining of the linked list, and works even if e was null (i.e. there was no collision at all and the created Entry is the first one with the given bucketIndex).

huangapple
  • 本文由 发表于 2020年3月4日 05:58:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/60516123.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定