java如何实现hash map链冲突解决

How do java implement hash map chain collision resolution

我知道我们可以使用链表来处理哈希映射的链冲突。但是,在Java中,hash map的实现使用了一个数组,我很好奇java是如何实现hash map链冲突解决的。我确实找到了这个 post:Collision resolution in Java HashMap .但是,这不是我要找的答案。

非常感谢。

HashMap 包含 Entry class 的数组。每个桶都有一个 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;
    }