jdk1.8 hashmap.split方法解析

  • Post author:
  • Post category:其他


/**
*和链表的修剪差不多
*/
final void split(HashMap<K,V> map, Node<K,V>[] tab, int index, int bit) {
    TreeNode<K,V> b = this;
    // Relink into lo and hi lists, preserving order
    TreeNode<K,V> loHead = null, loTail = null;
    TreeNode<K,V> hiHead = null, hiTail = null;
    int lc = 0, hc = 0;
    for (TreeNode<K,V> e = b, next; e != null; e = next) {
        next = (TreeNode<K,V>)e.next;
        e.next = null;
        if ((e.hash & bit) == 0) {
            if ((e.prev = loTail) == null)
                loHead = e;
            else
                loTail.next = e;
            loTail = e;
            ++lc;
        }
        else {
            if ((e.prev = hiTail) == null)
                hiHead = e;
            else
                hiTail.next = e;
            hiTail = e;
            ++hc;
        }
    }

    if (loHead != null) {
        if (lc <= UNTREEIFY_THRESHOLD)
        	//如果loHead上的树节点小于等于6个那就去树化变回单向链表
            tab[index] = loHead.untreeify(map);
        else {
        	//否则让索引位置的结点指向loHead树
            tab[index] = loHead;
            if (hiHead != null) //hiHead 不为空说明原来索引位置上的树少了,修剪过,否则没少,没修剪过就不用动
                loHead.treeify(tab);//那就树化
        }
    }
    if (hiHead != null) {
        if (hc <= UNTREEIFY_THRESHOLD)
            tab[index + bit] = hiHead.untreeify(map);
        else {
            tab[index + bit] = hiHead;
            if (loHead != null)
                hiHead.treeify(tab);
        }
    }
}



版权声明:本文为qsdnmd原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。