我知道我们可以使用链表来处理哈希映射的链式冲突。但是,在Java中,哈希映射实现使用数组,我很好奇java是如何实现哈希映射链冲突解决的。我确实找到了这篇文章:Collision resolution in Java HashMap。然而,这不是我想要的答案。
非常感谢。
发布于 2015-03-06 05:30:59
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;
}https://stackoverflow.com/questions/28892857
复制相似问题