重新去认识HashMap(Java8源码浅析)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/donggua3694857/article/details/79612983

加入新公司后一直忙于项目,疯狂加班,断更了N个月,一直没时间去管理自己所学习的新的知识(说白了就是懒。。。),前些天在头条上看到了一篇关于jdk5,6,7,8,9的一些区别的文章,虽然有所了解,但由于自己的项目中用的依旧还是1.6,因此并没有很多机会去了解一些新版本的一些特性(说白了还是懒。。。),想着之前自己貌似也写过一篇关于HashMap的源码解析(基于1.7),于是决定来看看1.8中到底有了些什么区别,重新去认识一下HashMap。

一、数据结构

这个1.8是在1.7的基础上加了个红黑树,数组还是数组,只不过由Entry数组变成了Node数组。链表还是链表,1.8中链表长度超过了8后会转变成红黑树(关于红黑树这个数据结构相信大家都是只是听过,并没有深入去理解,至少我是这样的。。。)。改成了红黑树,在链表过长的时候,即当hash值相等的元素较多时,查找时间会有一个大大的提升。

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;
        }
    }

可以对比一下1.7的Entry,二者其实还是一样的数据结构,这种做法我想也是为了兼容老版本的数据吧。
除此之外,还有红黑树的树节点

static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> {
        TreeNode<K,V> parent;  // red-black tree links
        TreeNode<K,V> left;
        TreeNode<K,V> right;
        TreeNode<K,V> prev;    // needed to unlink next upon deletion
        boolean red;
        TreeNode(int hash, K key, V val, Node<K,V> next) {
            super(hash, key, val, next);
        }
        ......
    }

二、存取实现

2.1 存

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)
            tab[i] = newNode(hash, key, value, null);
        else {
            Node<K,V> e; K k;
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
            else if (p instanceof TreeNode)
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            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;
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }

1.8的put方法比1.7丰富了很多,之前初始化数组的地方在HashMap的初始化方法中,现在放在类put方法里面,数据丢进去前先判断。hash方法也做了简化

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

如果在table上找到了位置,那就新建节点。如果找到且key一样,那就覆盖。
如果不一样,节点是树节点,那就往树上加节点;如果是链表节点,那就一边循环查找,有相同的key就覆盖,没有就加节点,在添加的过程中,如果发现链表长度大于8,结构就改成红黑树,再在红黑树的基础上添加节点。
在最后检查一下大小,是否超过了最大容量threshold,不够要扩容。

2.2 取

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))))
                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;
    }

查找没什么说的,1.8比1.7多那个红黑树结构,对查找效率有很大的提高。原先链表的查找
时间复杂度可能会达到O(n),即全部遍历;但是由于红黑树的特性,查找某一节点复杂度最差只有O(log n)。

三、扩容机制

我们直接看看源码

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;
            }
            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 {               // zero initial threshold signifies using defaults
            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) {
            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;
                    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;
    }

思想还是和1.7一样,与1.7不同的是,是在将老数组向新数组转移时,1.8做了一些优化。在1.7中,在确定索引位置的时候会有rehash的情况。而在1.8中,没有rehash的相关代码。说明在1.8中已经节省掉了这部分的时间。1.8中的resize方法中确认新下标是使用hash值与 数组长度 进行与运算,得到的是0 或者非零。如果是0 表示新位置下标不变,如果不是0那么表示位置有变动。如果(e.hash & oldCap) == 0,这就说明e.hash & (newCap-1)还会和 e.hash & (oldCap-1)一样。因为oldCap和newCap是2的次幂,并且newCap是oldCap的两倍,就相当于oldCap的唯一一个二进制的1向高位移动了一位。 每次扩容他都要对原来的红黑树进行拆解或重建,我觉得这部分应该也挺花时间的。具体我没做过实验,因为网上很多地方都说1.8的resize的方法有优化,我觉得不需要再次rehash是个亮点,别的都是为了查询效率的提升所填的坑。毕竟使用红黑树确实能提高查询效率,极限状态吧,一般情况我觉得也差不多其实。。。但是也不得不佩服大师的卓越思维。

猜你喜欢

转载自blog.csdn.net/donggua3694857/article/details/79612983
今日推荐