我想了解 Java 中 HashMap 的内部实现。我对“createEntry”方法感到困惑。
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++;
}
它创建一个条目对象 'e',然后将其放入另一个条目对象并将其存储到 bucket[bucketindex] 中,它还存储键和值。我无法理解在此处创建条目对象“e”的目的。有人可以解释一下吗。
问候
最佳答案
它获取桶中的前一个条目(即使它是null
)。然后它创建一个新条目,将其 next
条目设置为检索到的前一个条目。然后它将新条目设置为存储桶中的相同索引。
假设你在散列中有 3 个元素
0: [null]
1: [some entry]
2: [null]
而且你必须添加到索引 1
0: [null]
1: [new entry] -> [some entry]
2: [null]
类似地,添加到索引0
0: [newer entry] -> [null]
1: [new entry] -> [some entry]
2: [null]
关于java - 对 Java HashMap createEntry 方法的混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20720187/