HashMap源码解析

133 阅读11分钟

resize()扩容

若长度超过2^30(1073741824)则不进行扩容
  否则新的长度扩大的为之前数组长度的两倍。
  如果节点没有链表,用新数组计算节点位置,放入新数组中
  如果节点是树split()方法
  如果节点是链表(如果位置是0,直接放到新数组中位置不变,如果是其他位置,移动旧的数组个长度放入)1.7中放入链表会头尾变序
  返回新数组

    final Node<K,V>[] resize() {
        Node<K,V>[] oldTab = table;
        int oldCap = (oldTab == null) ? 0 : oldTab.length;
        int oldThr = threshold;
        int newCap, newThr = 0;
        if (oldCap > 0) {
            if (oldCap >= MAXIMUM_CAPACITY) {//MAXIMUM_CAPACITY = 1073741824,如果旧的数组长度大于最大长度
                threshold = Integer.MAX_VALUE;
                return oldTab;
            }
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                    oldCap >= DEFAULT_INITIAL_CAPACITY)//新的长度为旧的长度的两倍并且小于MAXIMUM_CAPACITY 并且旧的长度大于14
                newThr = oldThr << 1; // double threshold 扩大两倍
        }
        else if (oldThr > 0) // initial capacity was placed in threshold 如果初始阀值大于0,把初始阀值赋值给初始容量
            newCap = oldThr;
        else {               // zero initial threshold signifies using defaults 零初始阈值表示使用默认值。
            newCap = DEFAULT_INITIAL_CAPACITY;
            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
        }
        if (newThr == 0) {//若新的阀值为0
            float ft = (float)newCap * loadFactor;//新的容量*装载因子(默认0.75)
            newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
                    (int)ft : Integer.MAX_VALUE);//新的容量<MAXIMUM_CAPACITY 并且 ft<MAXIMUM_CAPACITY 则新的阀值为ft,否则为MAX_VALUE
        }
        threshold = newThr;
        @SuppressWarnings({"rawtypes","unchecked"})
        Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
        table = newTab;
        if (oldTab != null) {
            for (int j = 0; j < oldCap; ++j) {
                Node<K,V> e;
                if ((e = oldTab[j]) != null) {
                    oldTab[j] = null;
                    if (e.next == null)//e的链表是空,直接把e放入新的数组中
                        newTab[e.hash & (newCap - 1)] = e;
                    else if (e instanceof TreeNode)//如果节点是树
                        ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
                    else { // preserve order 保留顺序
                        Node<K,V> loHead = null, loTail = null;
                        Node<K,V> hiHead = null, hiTail = null;
                        Node<K,V> next;
                        do {
                            next = e.next;
                            if ((e.hash & oldCap) == 0) {//是否是第一位
                                if (loTail == null)
                                    loHead = e;
                                else
                                    loTail.next = e;
                                loTail = e;
                            }
                            else {//其他位置
                                if (hiTail == null)
                                    hiHead = e;
                                else
                                    hiTail.next = e;
                                hiTail = e;
                            }
                        } while ((e = next) != null);
                        if (loTail != null) {
                            loTail.next = null;
                            newTab[j] = loHead;
                        }
                        if (hiTail != null) {//移动原数组长度个位置
                            hiTail.next = null;
                            newTab[j + oldCap] = hiHead;
                        }
                    }
                }
            }
        }
        return newTab;
    }

hash(Object key)

static final int hash(Object key) {
    int h;
    return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}

split()来切割树,如果树的节点小于等于6就进行切割然后取消树化,否则就把树放入相应位置中

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) {//如果是位置0,双链头是loHead双链尾是loTail
            if ((e.prev = loTail) == null)
                loHead = e;
            else
                loTail.next = e;
            loTail = e;
            ++lc;
        }
        else {//如果不是位置0,双链头是hiHead双链尾是hiTail
            if ((e.prev = hiTail) == null)
                hiHead = e;
            else
                hiTail.next = e;
            hiTail = e;
            ++hc;
        }
    }

    if (loHead != null) {
        if (lc <= UNTREEIFY_THRESHOLD)//如果链的长度小于等于6,取消树化,把双链变成单链
            tab[index] = loHead.untreeify(map);
        else {
            tab[index] = loHead;//放入0位置中
            if (hiHead != null) // (else is already treeified)
                loHead.treeify(tab);
        }
    }
    if (hiHead != null) {
        if (hc <= UNTREEIFY_THRESHOLD)//如果链的长度小于等于6,取消树化,把双链变成单链
            tab[index + bit] = hiHead.untreeify(map);
        else {
            tab[index + bit] = hiHead;//放入index+旧长度位置中
            if (loHead != null)
                hiHead.treeify(tab);
        }
    }
}

untreeify()取消树化

final Node<K,V> untreeify(HashMap<K,V> map) {
    Node<K,V> hd = null, tl = null;
    for (Node<K,V> q = this; q != null; q = q.next) {
        Node<K,V> p = map.replacementNode(q, null);
        if (tl == null)
            hd = p;
        else
            tl.next = p;
        tl = p;
    }
    return hd;
}

get()

final Node<K,V> getNode(int hash, Object key) {
    Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
    if ((tab = table) != null && (n = tab.length) > 0 &&
            (first = tab[(n - 1) & hash]) != null) {
        if (first.hash == hash && // always check first node
                ((k = first.key) == key || (key != null && key.equals(k))))//若hash值相同,key也相同,返回当前节点
            return first;
        if ((e = first.next) != null) {//如果节点的next不为空,则可能是链表或者红黑树
            if (first instanceof TreeNode)//如果节点是红黑树
                return ((TreeNode<K,V>)first).getTreeNode(hash, key);
            do {//如果链表,循环获取链表中相同key和key的hash的节点并返回
                if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                    return e;
            } while ((e = e.next) != null);
        }
    }
    return null;
}

getTreeNode中主要是find()

/**
 * 如果要查找的hash小于p节点就查左边,
 * 如果查找的hash大于p节点就去右边查,
 * 左边空查右边,
 * 右边空查左边
 * 递归查找
 */
final TreeNode<K,V> find(int h, Object k, Class<?> kc) {
    TreeNode<K,V> p = this;
    do {
        int ph, dir; K pk;
        TreeNode<K,V> pl = p.left, pr = p.right, q;
        if ((ph = p.hash) > h)
            p = pl;
        else if (ph < h)
            p = pr;
        else if ((pk = p.key) == k || (k != null && k.equals(pk)))
            return p;
        else if (pl == null)
            p = pr;
        else if (pr == null)
            p = pl;
        else if ((kc != null ||
                (kc = comparableClassFor(k)) != null) &&
                (dir = compareComparables(kc, k, pk)) != 0)
            p = (dir < 0) ? pl : pr;
        else if ((q = pr.find(h, k, kc)) != null)
            return q;
        else
            p = pl;
    } while (p != null);
    return null;
}

put()

若数组长度为空进行扩容
若算出的位置为空,在当前位置新建新节点
若位置不为空,则确定是否value重复、确定是不是树,确定是不是链表
 若key和hash相同,则用新value替换旧value,并把旧value返回
 如果是树,添加新节点
 若链表则去新增链节点,如果新增的节点大等8折转成树,若在链中key和hash相同,则用新value替换旧value,并把旧value返回

final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
               boolean evict) {
    Node<K,V>[] tab; Node<K,V> p; int n, i;
    if ((tab = table) == null || (n = tab.length) == 0)//若数组长度为空则进行扩容
        n = (tab = resize()).length;
    if ((p = tab[i = (n - 1) & hash]) == null)//(n-1) & hash 算出来的值,小于n,相当于hash值 % n ,若算出的位置为空,新建新节点
        tab[i] = newNode(hash, key, value, null);
    else {//若位置不为空,则确定是否value重复、确定是不是树,确定是不是链表
        Node<K,V> e; K k;
        if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))//若key和hash相同,则用新value替换旧value,并把旧value返回
            e = p;
        else if (p instanceof TreeNode)//如果是树,添加新节点
            e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
        else {
            for (int binCount = 0; ; ++binCount) {//是链表则去新增链节点,如果新增的节点大等8折转成树,若在链中key和hash相同,则用新value替换旧value,并把旧value返回
                if ((e = p.next) == null) {
                    p.next = newNode(hash, key, value, null);
                    if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                        treeifyBin(tab, hash);
                    break;
                }
                if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                    break;
                p = e;
            }
        }
        if (e != null) { // existing mapping for key 此时做新value替换旧value
            V oldValue = e.value;
            if (!onlyIfAbsent || oldValue == null)
                e.value = value;
            afterNodeAccess(e);
            return oldValue;
        }
    }
    ++modCount;//记录操作计数,并发计数,替换旧的value不算操作
    if (++size > threshold)//若size大于阀值则进行扩容
        resize();
    afterNodeInsertion(evict);
    return null;
}

转自美团技术团队

putTreeVal()

final TreeNode<K,V> putTreeVal(HashMap<K,V> map, Node<K,V>[] tab,
                               int h, K k, V v) {
    Class<?> kc = null;
    boolean searched = false;
    TreeNode<K,V> root = (parent != null) ? root() : this;
    for (TreeNode<K,V> p = root;;) {
        int dir, ph; K pk;
        if ((ph = p.hash) > h)//传入的hash小于p的hash 则dir = -1;
            dir = -1;
        else if (ph < h)//传入的hash大雨p的hash 则dir = 1;
            dir = 1;
        else if ((pk = p.key) == k || (k != null && k.equals(pk)))//p的key和传入的key相同,用新的value替换旧的value并且把旧value返回
            return p;
        else if ((kc == null &&
                (kc = comparableClassFor(k)) == null) ||
                (dir = compareComparables(kc, k, pk)) == 0) {
            if (!searched) {
                TreeNode<K,V> q, ch;
                searched = true;
                if (((ch = p.left) != null &&
                        (q = ch.find(h, k, kc)) != null) ||
                        ((ch = p.right) != null &&
                                (q = ch.find(h, k, kc)) != null))
                    return q;
            }
            dir = tieBreakOrder(k, pk);
        }

        TreeNode<K,V> xp = p;
        if ((p = (dir <= 0) ? p.left : p.right) == null) {//dir为负获取p的左子树,dir为正获取p的右子树,并且赋值给p,判断p是否为空
            Node<K,V> xpn = xp.next;
            TreeNode<K,V> x = map.newTreeNode(h, k, v, xpn);
            if (dir <= 0)//小的放左边,大的放右边,小的放左边
                xp.left = x;
            else
                xp.right = x;
            xp.next = x;
            x.parent = x.prev = xp;
            if (xpn != null)
                ((TreeNode<K,V>)xpn).prev = x;
            moveRootToFront(tab, balanceInsertion(root, x));//先平衡在移动root到链表首节点
            return null;
        }
        //不为空,继续循环,直到找到为空的节点
    }
}

balanceInsertion()

/**
 * 平衡该树
 * @param root
 * @param x
 * @param <K>
 * @param <V>
 * @return
 */
static <K,V> TreeNode<K,V> balanceInsertion(TreeNode<K,V> root,
                                            TreeNode<K,V> x) {
    x.red = true;//当前节点为red
    for (TreeNode<K,V> xp, xpp, xppl, xppr;;) {
        if ((xp = x.parent) == null) {//当前节点的父节点为xp为空时,说明时根节点,把节点返回
            x.red = false;
            return x;
        }
        else if (!xp.red || (xpp = xp.parent) == null)//如果该节点不是红的或者xp的父节点xpp为空,返回该root,如果有两个节点时如此
            return root;
        if (xp == (xppl = xpp.left)) {//x节点的祖父节点的左子树为xppl,若xppl和xp相等
            if ((xppr = xpp.right) != null && xppr.red) {//x节点的祖父节点的右节点为xppr,若xppr不为空,并且xppr为red
                xppr.red = false;
                xp.red = false;
                xpp.red = true;
                x = xpp;
            }
            else {//x节点的祖父节点的右节点为xppr,若xppr为空或者xppr为黑
                if (x == xp.right) {//若x的父节点的右子树为x
                    root = rotateLeft(root, x = xp);
                    xpp = (xp = x.parent) == null ? null : xp.parent;
                }
                if (xp != null) {//x的父节点不是空
                    xp.red = false;//x的父节点为黑
                    if (xpp != null) {//x的祖父节点不是空
                        xpp.red = true;//x的祖父节点为红
                        root = rotateRight(root, xpp);//右旋
                    }
                }
            }
        }
        else {
            if (xppl != null && xppl.red) {
                xppl.red = false;
                xp.red = false;
                xpp.red = true;
                x = xpp;
            }
            else {
                if (x == xp.left) {
                    root = rotateRight(root, x = xp);
                    xpp = (xp = x.parent) == null ? null : xp.parent;
                }
                if (xp != null) {
                    xp.red = false;
                    if (xpp != null) {
                        xpp.red = true;
                        root = rotateLeft(root, xpp);//左旋
                    }
                }
            }
        }
    }
}

左旋和右旋

static <K,V> TreeNode<K,V> rotateLeft(TreeNode<K,V> root,
                                      TreeNode<K,V> p) {
    TreeNode<K,V> r, pp, rl;
    if (p != null && (r = p.right) != null) {
        if ((rl = p.right = r.left) != null)
            rl.parent = p;
        if ((pp = r.parent = p.parent) == null)
            (root = r).red = false;
        else if (pp.left == p)
            pp.left = r;
        else
            pp.right = r;
        r.left = p;
        p.parent = r;
    }
    return root;
}

static <K,V> TreeNode<K,V> rotateRight(TreeNode<K,V> root,
                                       TreeNode<K,V> p) {//右旋
    TreeNode<K,V> l, pp, lr;
    if (p != null && (l = p.left) != null) {//p节点不是空,p节点的左子树为l不为空
        if ((lr = p.left = l.right) != null)//p的左子树的右子树赋值给p的左子树为lr不为空
            lr.parent = p;
        if ((pp = l.parent = p.parent) == null)//p的父节点赋值给p的左子树的parent,赋值给pp,若pp为空
            (root = l).red = false;//l变为根节点,并且red=false
        else if (pp.right == p)
            pp.right = l;
        else
            pp.left = l;
        l.right = p;
        p.parent = l;
    }
    return root;
}

moveRootToFront()

static <K,V> void moveRootToFront(Node<K,V>[] tab, TreeNode<K,V> root) {
    int n;
    if (root != null && tab != null && (n = tab.length) > 0) {
        int index = (n - 1) & root.hash;
        TreeNode<K,V> first = (TreeNode<K,V>)tab[index];//first指向数组中链表第一个节点
        if (root != first) {//root是新转化成红黑树的root,first是之前tab中的tab【index】
            Node<K,V> rn;
            tab[index] = root;//把root放到数组中index的位置上
            TreeNode<K,V> rp = root.prev;
            if ((rn = root.next) != null)
                ((TreeNode<K,V>)rn).prev = rp;
            if (rp != null)
                rp.next = rn;
            if (first != null)
                first.prev = root;
            root.next = first;
            root.prev = null;
        }
        //使用断言来校验结构
        assert checkInvariants(root);
    }
}

checkInvariants()

static <K,V> boolean checkInvariants(TreeNode<K,V> t) {
    TreeNode<K,V> tp = t.parent, tl = t.left, tr = t.right,
            tb = t.prev, tn = (TreeNode<K,V>)t.next;
    if (tb != null && tb.next != t)//t的前驱节点不为空 并且 t的前驱节点的后继节点不为t(应该为t)
        return false;
    if (tn != null && tn.prev != t)//t的后继节点不为空 并且 t的后继节点的前驱节点不为t(应该为t)
        return false;
    if (tp != null && t != tp.left && t != tp.right)//t的父节点不是空 并且 t不是tp的左子树 并且 t也不是tp的右子树
        return false;
    if (tl != null && (tl.parent != t || tl.hash > t.hash))//t的左子树不是空 并且 (t的左子树不是t 或者 t的左子树的hash值大于t的hash值)
        return false;
    if (tr != null && (tr.parent != t || tr.hash < t.hash))//t的右子树不是空 并且 (t的右子树不是t 或者 t的右子树的hash值小于t的hash值)
        return false;
    if (t.red && tl != null && tl.red && tr != null && tr.red)//t是红 并且 t的左子树不是空 并且 t的左子树是红 并且 t的右子树不为空 并且 t的右子树为红(就是根左右都红)
        return false;
    if (tl != null && !checkInvariants(tl))//tl不是空的 并且 校验递归校验tl为false
        return false;
    if (tr != null && !checkInvariants(tr))//tr不是空的 并且 校验递归校验tr为false
        return false;
    return true;
}

treeifyBin()进行树化

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)
            hd.treeify(tab);
    }
}

treeify()进行真正的树化

final void treeify(Node<K,V>[] tab) {
    TreeNode<K,V> root = null;
    //循环当前的树,让它成为红黑树
    for (TreeNode<K,V> x = this, next; x != null; x = next) {
        next = (TreeNode<K,V>)x.next;
        x.left = x.right = null;
        if (root == null) {
            x.parent = null;
            x.red = false;
            root = x;
        }
        else {
            K k = x.key;
            int h = x.hash;
            Class<?> kc = null;
            for (TreeNode<K,V> p = root;;) {
                int dir, ph;
                K pk = p.key;
                if ((ph = p.hash) > h)
                    dir = -1;
                else if (ph < h)
                    dir = 1;
                else if ((kc == null &&
                        (kc = comparableClassFor(k)) == null) ||
                        (dir = compareComparables(kc, k, pk)) == 0)
                    dir = tieBreakOrder(k, pk);

                TreeNode<K,V> xp = p;
                //如果dir为负,放左边,dir为正,放右边(大的放左边,小的放右边)
                if ((p = (dir <= 0) ? p.left : p.right) == null) {
                    x.parent = xp;
                    if (dir <= 0)
                        xp.left = x;
                    else
                        xp.right = x;
                    //去平衡二叉树
                    root = balanceInsertion(root, x);
                    break;
                }
            }
        }
    }
    moveRootToFront(tab, root);
}

总结:
  HashMap是一个由数组、链表、红黑树构成的数据结构。如果不设置初始大小,默认大小为16,如果设置初始大小,大小为2的倍数,则为该值,如果不是2的倍数,则向上取2的倍数(如设置100,取128)。默认的装载因子是0.75,每次扩容会判断当前所用空间是否是当前空间的0.75,大于0.75则扩容。