我知道我们可以使用链表来处理 HashMap 的链冲突。然而,在Java中, HashMap 实现使用数组,我很好奇java是如何实现 HashMap 链冲突解决的。我确实找到了这篇文章:Collision resolution in Java HashMap 。然而,这不是我正在寻找的答案。
非常感谢。
最佳答案
HashMap
包含一个Entry
类的数组。每个存储桶都有一个 LinkedList
实现。每个桶都指向hashCode
,也就是说,如果发生冲突,则新条目将添加到同一桶中列表的末尾。
看看这段代码:
public V put(K key, V value) {
if (key == null)
return putForNullKey(value);
int hash = hash(key.hashCode());
int i = indexFor(hash, table.length); // get table/ bucket index
for (Entry<K,V> e = table[i]; e != null; e = e.next) { // walk through the list of nodes
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; // return old value if found
}
}
modCount++;
addEntry(hash, key, value, i); // add new value if not found
return null;
}
关于java - java如何实现hashmap链碰撞解决,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28892857/