首页 > 解决方案 > 关于 HashMap#treeifyBin 的困惑

问题描述

我正在阅读有关HashMap#treeifyBin函数的源代码。

很困惑为什么要检查

if ((tab[index] = hd) != null)

因为它之前已经检查过了

(e = tab[index = (n - 1) & hash]) != null

代码:

final void treeifyBin(Node<K,V>[] tab, int hash) {
    int n, index; Node<K,V> e;
    if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
        resize();
    else if ((e = tab[index = (n - 1) & hash]) != null) {
        TreeNode<K,V> hd = null, tl = null;
        do {
            TreeNode<K,V> p = replacementTreeNode(e, null);
            if (tl == null)
                hd = p;
            else {
                p.prev = tl;
                tl.next = p;
            }
            tl = p;
        } while ((e = e.next) != null);
        if ((tab[index] = hd) != null)  // why do we need this line?
            hd.treeify(tab);
    }
}

标签: javahashmap

解决方案


推荐阅读