标题翻译
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<K,V> e = new Entry<K,V>(hash, key, value)
table[bucketIndex] = e;
答案1
得分: 2
因为在HashMap
中可能会发生冲突(即产生相同的bucketIndex
的不同键)。如果按照你提出的建议去做,那么在发生冲突的情况下,最后插入的元素将以一种几乎不可预测的方式删除先前的元素。
Entry
被实现为一种链表,因此它实际上被命名得有些不准确,实际上它是条目链表的一个节点。这就是为什么在Entry
构造函数中将e
作为最后一个参数传递的原因。
创建一个引用先前条目(e
)的新Entry
,并将其添加到与e
相同的位置,就是在链表开头插入新节点的操作,即使e
为null
(即根本没有发生冲突,而创建的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
).
专注分享java语言的经验与见解,让所有开发者获益!
评论