JDK 1.8之 HashMap 源码分析

转载请注明出处:http://blog.csdn.net/crazy1235/article/details/75579654

与JDK1.7中HashMap的实现相比,JDK1.8做了如下改动:

  • hash()函数算法修改

  • table数组的类型,由Entry改成了Node

  • HashMap存储数据的结构由数组+链表,进化成了 数组+链表+(RBT)红黑树

即使加载因子和Hash算法设计的再合理,也免不了出现拉链过长的情况,所以JDK1.8中,当拉链超过一定长度(8)时,会将链表转成一颗红黑树!

《JDK 1.8之 HashMap 源码分析》

(图片转自网络)

重点关注与1.7中实现不同的地方!

构造函数

    public HashMap(int initialCapacity, float loadFactor) {
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal initial capacity: " +
                                               initialCapacity);
        if (initialCapacity > MAXIMUM_CAPACITY)
            initialCapacity = MAXIMUM_CAPACITY;
        if (loadFactor <= 0 || Float.isNaN(loadFactor))
            throw new IllegalArgumentException("Illegal load factor: " +
                                               loadFactor);
        this.loadFactor = loadFactor;
        this.threshold = tableSizeFor(initialCapacity); // 初始化阈值
    }
    /** * 根据容量计算阈值(临界值) */
    static final int tableSizeFor(int cap) {
        int n = cap - 1;
        n |= n >>> 1;
        n |= n >>> 2;
        n |= n >>> 4;
        n |= n >>> 8;
        n |= n >>> 16;
        return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
    }

Node

    // 与1.7中 Entry的内容大同小异,只是换了个名称而已!
    static class Node<K,V> implements Map.Entry<K,V> {
        final int hash;
        final K key;
        V value;
        Node<K,V> next; // 指向下一个节点

        Node(int hash, K key, V value, Node<K,V> next) {
            this.hash = hash;
            this.key = key;
            this.value = value;
            this.next = next;
        }

        public final K getKey()        { return key; }
        public final V getValue()      { return value; }
        public final String toString() { return key + "=" + value; }

        public final int hashCode() {
            return Objects.hashCode(key) ^ Objects.hashCode(value);
        }

        public final V setValue(V newValue) {
            V oldValue = value;
            value = newValue;
            return oldValue;
        }

        public final boolean equals(Object o) {
            if (o == this)
                return true;
            if (o instanceof Map.Entry) {
                Map.Entry<?,?> e = (Map.Entry<?,?>)o;
                if (Objects.equals(key, e.getKey()) &&
                    Objects.equals(value, e.getValue()))
                    return true;
            }
            return false;
        }
    }

hash

相比JDK1.7中的hash()函数,1.8做了简化!

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

如果key是null,则返回0

如果key不是null,则得到key的hashCode值,右移16位之后,做异或运算!(高位参与运算

Hash算法计算得到的结果越分散,发生碰撞的几率就越小,map的存取效率就会越高!

《JDK 1.8之 HashMap 源码分析》

(图片转自网路)

put

// 这个常量的意思就是,当一个bucket是一个链表,链表个数大于等于8时,就要树状化,也就是要从链表结构变成红黑树结构
static final int TREEIFY_THRESHOLD = 8;

先来看看put()的实现

    // 如果已经存在key对应的节点,则覆盖value值
    public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }
    // 如果已经存在key对应的节点,不覆盖value值
    @Override
    public V putIfAbsent(K key, V value) {
        return putVal(hash(key), key, value, true, true);
    }

重点来看 putVal() 函数!

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) // 如果map为空时,调用resize()进行初始化!
            n = (tab = resize()).length;
        if ((p = tab[i = (n - 1) & hash]) == null) // 如果没有在数组中找到对应的节点,则直接插入一个Node (未发生碰撞)
            tab[i] = newNode(hash, key, value, null);
        else {     // 找到了(n - 1) & hash 对应下标的数组(tab)中的节点 ,也就是发生了碰撞
            Node<K,V> e; K k;

            // 1. hash值一样,key值一样,则找到目标Node
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))

            // 2. 数组中找到的这个节点p是TreeNode类型,则需要插入到RBT里面一个节点
            else if (p instanceof TreeNode)
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            else {

            // 3. 不是TreeNode类型,则表示是一个链表,这里就类似与jdk1.7中的操作
                for (int binCount = 0; ; ++binCount) { // 遍历链表
                    if ((e = p.next) == null) {

                        // 4. 此时查找当前链表的次数已经超过7个,则需要链表RBT化!

                        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)))) // 5. 找到链表中对应的节点
                        break;
                    p = e;
                }
            }
            // 如果e不为空,则表示在HashMap中找到了对应的节点
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                // 当onlyIfAbsent=false 或者key对应的旧value为空时,用新的value替换旧value
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount; // 操作次数+1
        if (++size > threshold) // hashmap节点个数+1,并判断是否超过阈值,如果超过则重建结构!
            resize();
        afterNodeInsertion(evict);
        return null;
    }

下面主要关注是三个函数:

  • putTreeVal(this, tab, hash, key, value);

  • treeifyBin(tab, hash);

  • treeify();

  • resize();

putTreeVal() 函数的目的就是往RBT中插入一个节点,但是牵涉到平衡化的方法,所以相对来讲难一些!

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);
        }
    }
    // 将Node对象转成TreeNode对象
    TreeNode<K,V> replacementTreeNode(Node<K,V> p, Node<K,V> next) {
        return new TreeNode<>(p.hash, p.key, p.value, next);
    }

treeify 主要涉及二叉树的创建,就是一个一个add节点,涉及到平衡的算法!

先来说下一红黑树的定义:

  • 任何一个节点都是有颜色的,黑色或者红色

  • 根节点是黑色的

  • 父子结点之间不能出现两个连续的红色节点

  • 任何一个节点向下遍历到其子孙的叶子节点,所经历的黑色结点个数必须相等

  • 空节点被认为是黑色的

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;
                    // 遍历root,插入到RBTree中
                    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;
                        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);
        }

插入结点,只有插入节点的父节点是空色的,才需要考虑变换结点的顺序进行平衡。
总结下来,有三种情况需要反转

  • 叔叔节点也是红色
  • 叔叔节点为空,且祖父结点、父节点和新节点在一条斜线上
  • 叔叔节点为空,且祖父结点、父节点和新节点不在一条斜线上
static <K,V> TreeNode<K,V> balanceInsertion(TreeNode<K,V> root,
                                                    TreeNode<K,V> x) {
            // 新节点置为红色 
            x.red = true;
            for (TreeNode<K,V> xp, xpp, xppl, xppr;;) {
                // x的父节点是空时,x即为根节点,将x变为黑色
                if ((xp = x.parent) == null) { 
                    x.red = false;
                    return x;
                }
                //此时不需要平衡,直接返回结合!
                else if (!xp.red || (xpp = xp.parent) == null)
                    return root;
                // 如果x的父节点是x的祖父节点的左节点
                if (xp == (xppl = xpp.left)) {
                    // 如果xp的兄弟节点是红色,此时需要反转
                    if ((xppr = xpp.right) != null && xppr.red) {
                        xppr.red = false;
                        xp.red = false;
                        xpp.red = true;
                        x = xpp;
                    }
                    else {
                        如果x是父节点的右节点,则此时需要先左旋后右旋
                        if (x == xp.right) {
                            root = rotateLeft(root, x = xp); // 左旋
                            xpp = (xp = x.parent) == null ? null : xp.parent;
                        }
                        if (xp != null) {
                            xp.red = false;
                            if (xpp != null) {
                                xpp.red = true;
                                root = rotateRight(root, xpp); // 右旋
                            }
                        }
                    }
                }
                // 这里else分支是上面if分支的镜像,对称操作即可
                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);
                            }
                        }
                    }
                }
            }
        }

get

    // 根据key值找到value
    public V get(Object key) {
        Node<K,V> e;
        return (e = getNode(hash(key), key)) == null ? null : e.value;
    }
    /** * Implements Map.get and related methods * * @param hash hash for key * @param key the key * @return the node, or null if none */
    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) {

            // always check first node
            if (first.hash == hash && 
                ((k = first.key) == key || (key != null && key.equals(k))))
                return first;
            if ((e = first.next) != null) {

                // 如果是红黑树结构则去查询红黑树
                if (first instanceof TreeNode) 
                    return ((TreeNode<K,V>)first).getTreeNode(hash, key);

                // 如果不是则遍历链表
                do {
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        return e;
                } while ((e = e.next) != null);
            }
        }
        return null;
    }

此时主要关注在RBT中查找一个节点的函数原理

        /** * Calls find for root node. */
        final TreeNode<K,V> getTreeNode(int h, Object k) {
            return ((parent != null) ? root() : this).find(h, k, null);
        }
    // 实际上就是一个遍历红黑树查找节点的函数
    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) // h小于p(根节点)的hash值,则h代表的节点在p的左子树上
                    p = pl;
                else if (ph < h) // h大于ph值时,h代表的节点在p的右子树上
                    p = pr;
                // 如果hash中相等,且key值相等,则命中节点p。
                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;
        }
  • 发生了碰撞的意思就是遇到了在同一个bucket上的节点

resize

扩容

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) {
                threshold = Integer.MAX_VALUE;
                return oldTab;
            }
            // 没有超过最大值,左移一位(扩大1倍)
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                     oldCap >= DEFAULT_INITIAL_CAPACITY)
                // 将阈值也扩大一倍
                newThr = oldThr << 1; // double threshold
        }
        else if (oldThr > 0) // initial capacity was placed in threshold
            newCap = oldThr;
        else {               // 这个分支只有在调用空构造函数时,初始化走这个
            newCap = DEFAULT_INITIAL_CAPACITY;
            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
        }
        if (newThr == 0) {
            float ft = (float)newCap * loadFactor;
            newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
                      (int)ft : Integer.MAX_VALUE);
        }
        threshold = newThr;
        @SuppressWarnings({"rawtypes","unchecked"})
        // 创建新的数组
            Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
        table = newTab;
        if (oldTab != null) { //扩容时走这个if
            for (int j = 0; j < oldCap; ++j) { // 遍历旧数组
                Node<K,V> e;
                if ((e = oldTab[j]) != null) {
                    oldTab[j] = null; //释放旧数组中占据的资源
                    if (e.next == null)
                        newTab[e.hash & (newCap - 1)] = e; //hash运算并取模,放到新数组中
                    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;
                            }
                            // 原索引+oldCap
                            else {
                                if (hiTail == null)
                                    hiHead = e;
                                else
                                    hiTail.next = e;
                                hiTail = e;
                            }
                        } while ((e = next) != null);
                        // 原索引放到bucket里
                        if (loTail != null) {
                            loTail.next = null;
                            newTab[j] = loHead;
                        }
                        // 原索引+oldCap放到bucket里
                        if (hiTail != null) {
                            hiTail.next = null;
                            newTab[j + oldCap] = hiHead;
                        }
                    }
                }
            }
        }
        return newTab;
    }

参考

http://www.cnblogs.com/dennyzhangdd/p/6745282.html
https://tech.meituan.com/java-hashmap.html
http://www.jianshu.com/p/e694f1e868ec

关于红黑树的具体实现操作可以参考美团的这篇文章:
https://zhuanlan.zhihu.com/p/24367771

    原文作者:月盡天明
    原文地址: https://blog.csdn.net/crazy1235/article/details/75579654
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞