美文网首页
HashMap源码分析(JDK1.8)

HashMap源码分析(JDK1.8)

作者: ohjam | 来源:发表于2018-09-12 12:05 被阅读17次

    HashMap JDK1.8 概述

    在之前的文章我们分析了在JDK1.7之前的HashMap的代码实现,现在来看一下JDK1.8的HashMap代码实现有什么变化,然后分析一下为什么需要这种变化。
    在进入代码之前,先要对JDK1.8之后的HashMap有个基本认识:跟JDK1.7相比,为了解决1.7之前的HashMap可能出现的数组中链表长度很长,查找效率低的情况,1.8中引入了红黑树的数据结构。
    新增了以下重要参数

        static final int TREEIFY_THRESHOLD = 8;
        static final int UNTREEIFY_THRESHOLD = 6;
        static final int MIN_TREEIFY_CAPACITY = 64;
    
    • TREEIFY_THRESHOLD:链表转成红黑树的阈值,当链表长度大于该值时,且数组容量达到最小树化阈值,则将链表转换成红黑树。
    • UNTREEIFY_THRESHOLD:红黑树转为链表的阈值,当在resize中发现当前数据结构为红黑树,调用split时,在方法中会进行判断,小于该值则转为链表。
    • MIN_TREEIFY_CAPACITY:最小树化阈值,即当散列桶链表长度已经达到链表转成红黑树的阈值TREEIFY_THRESHOLD时,还要判断数组容量是否达到该阈值,如果不满足这两个条件,数组中元素太多时则只进行普通的扩容,若满足这两个条件,则树化。

    接下来我们从常用的put方法和get方法入手看一下HashMap的变化


    Put方法

    先找到put方法

        public V put(K key, V value) {
            return putVal(hash(key), key, value, false, 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;
            // 判断HashMap内的数组是否为空,若为空则使用resize初始化数组
            // 这也是HashMap初始化的时机
            if ((tab = table) == null || (n = tab.length) == 0)
                n = (tab = resize()).length;
            // 根据key的hash值计算出数组索引i,相当于1.7中的indexFor()
            // 判断tab[i]是否存在冲突,若不存在直接插入
            if ((p = tab[i = (n - 1) & hash]) == null)
                tab[i] = newNode(hash, key, value, null);
            else {
                // 若存在,则如下操作:
                // 情况1:当前位置的key和插入的key是否相同
                // 情况2:准备插入的位置的数据结构是否为红黑树
                // 情况3:前面两种都不满足则当前位置为链表
                Node<K,V> e; K k;
                // 情况1 用新值替代旧值
                if (p.hash == hash &&
                    ((k = p.key) == key || (key != null && key.equals(k))))
                    e = p;
                // 情况2  数据结构为红黑树
                // 在红黑树中插入或者更新值
                else if (p instanceof TreeNode)
                    e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
                // 情况3  数据结构为链表
                // 遍历链表,若链表中不存在该key,则尾插法插到链表尾部(JDK1.7使用头插法)
                // 若链表中存在该key,则更新值
                else {
                    for (int binCount = 0; ; ++binCount) {
                        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
                    V oldValue = e.value;
                    if (!onlyIfAbsent || oldValue == null)
                        e.value = value;
                    afterNodeAccess(e);
                    return oldValue;
                }
            }
            ++modCount;
            // 判断size,若大于threshold容量则进行扩容操作
            if (++size > threshold)
                resize();
            afterNodeInsertion(evict);
            return null;
        }
    

    putVal中,在红黑树情况下插入值时调用的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)
                        dir = -1;
                    else if (ph < h)
                        dir = 1;
                    else if ((pk = p.key) == k || (k != null && k.equals(pk)))
                        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) {
                        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));
                        return null;
                    }
                }
            }
    

    HashMap初始化或者扩容时调用的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;
                }
                // 当前容量不超过最大容量,则扩容2倍
                else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                         oldCap >= DEFAULT_INITIAL_CAPACITY)
                    newThr = oldThr << 1; // double threshold
            }
            // 赋值默认的threshold
            else if (oldThr > 0) // initial capacity was placed in threshold
                newCap = oldThr;
            // HashMap初始化的情况
            else {               // zero initial threshold signifies using defaults
                newCap = DEFAULT_INITIAL_CAPACITY;
                newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
            }
            // 计算新的数组阈值threshold
            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) {
                // 遍历HashMap,重新排列散列桶
                for (int j = 0; j < oldCap; ++j) {
                    Node<K,V> e;
                    if ((e = oldTab[j]) != null) {
                        oldTab[j] = null;
                        // 数组tab[i]位置只有一个元素,直接计算放置元素
                        if (e.next == null)
                            newTab[e.hash & (newCap - 1)] = e;
                        // 如果是红黑树结构,调用split
                        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;
                                // 跟下面的else分链,将长的链表分为两条链表
                                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);
                            // 一条链表放在 newTab[j]位置
                            if (loTail != null) {
                                loTail.next = null;
                                newTab[j] = loHead;
                            }
                            // 一条链表放在 newTab[j + oldCap]位置
                            if (hiTail != null) {
                                hiTail.next = null;
                                newTab[j + oldCap] = hiHead;
                            }
                        }
                    }
                }
            }
            return newTab;
        }
    

    总的来说,在1.7中,put方法插入元素到链表时,是用的头插法,在1.8中式用的尾插法,插入时还需要做一步判断:判断是插入红黑树还是链表, resize时,扩容后重新排列散列桶还有个这样的判断条件(e.hash & oldCap) == 0,可以将一条链分为两条链,一条在原始位置,一条在原始位置+扩容前容量值的位置,
    以上就是putresize


    Get方法

    看一下get方法

        public V get(Object key) {
            Node<K,V> e;
            return (e = getNode(hash(key), key)) == null ? null : e.value;
        }
    

    get方法中调用了getNode方法

        final Node<K,V> getNode(int hash, Object key) {
            Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
            // 通过hash值计算出数组位置
            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))))
                    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;
        }
    

    总的来说,get方法就是先根据hash值找到hashmap中的散列桶位置,先判断是否在改位置第一个元素,然后判断是红黑树或者是链表进行取值,以上就是get方法流程。


    计算hash值

    除了putget方法的区别,看一下hash方法有什么变化
    在jdk1.7中:

        final int hash(Object k) {
            int h = hashSeed;
            if (0 != h && k instanceof String) {
                return sun.misc.Hashing.stringHash32((String) k);
            }
            // 异或
            h ^= k.hashCode();
    
            // This function ensures that hashCodes that differ only by
            // constant multiples at each bit position have a bounded
            // number of collisions (approximately 8 at default load factor).
            h ^= (h >>> 20) ^ (h >>> 12);
            return h ^ (h >>> 7) ^ (h >>> 4);
        }
    

    在jdk1.8中:

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

    可见在JDK1.8中hash变精简了

    相关文章

      网友评论

          本文标题:HashMap源码分析(JDK1.8)

          本文链接:https://www.haomeiwen.com/subject/zdtcgftx.html