HashMap的put操作及扩容函数的源码分析 1.8

1 put操作

  final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        //tab即bucket数组 n为数组长度
        Node<K,V>[] tab; Node<K,V> p; int n, i;
        //如果bucket数组为空
        if ((tab = table) == null || (n = tab.length) == 0)
            //扩容 n为扩容后bucket数组的长度 即原来的2倍
            n = (tab = resize()).length;
        //将待插入node的hash&(n-1)后得到索引,如果该索引处为空
        if ((p = tab[i = (n - 1) & hash]) == null)
            //将待插入node放入的该索引处
            tab[i] = newNode(hash, key, value, null);
        else {
            //p为上一步计算得索引下的头结点,k是p的key值
            Node<K,V> e; K k;
            //hash相等,并且key也相等,则该key存在,将p赋给e
            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) {
                    //如果p的后继为空
                    if ((e = p.next) == null) {
                        //将插入到p的后继
                        p.next = newNode(hash, key, value, null);
                        //当node数大于等于8时,转为红黑树
                        //插入一个结点后,node已经是8个了,然而此时binCount还 
                        //未更新仍是7;所以这里是binCount>=8-1.
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            treeifyBin(tab, hash);
                        break;
                    }
                    //key值存在,终止循环
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    //p指针沿链表下移
                    p = e;
                }
            }
            //已存在的关于key的键值对
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                //onlyIfAbsent表示是否仅在oldValue为空时更新键值对
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }

2、扩容


    final Node<K,V>[] resize() {
        //原bucket数组
        Node<K,V>[] oldTab = table;
        //原bucket数组的容量
        int oldCap = (oldTab == null) ? 0 : oldTab.length;
        int oldThr = threshold;
        
        int newCap, newThr = 0;
        if (oldCap > 0) {
            //容量已经最大了,返回原bucket数组,随你怎么碰撞也没办法了
            if (oldCap >= MAXIMUM_CAPACITY) {
                threshold = Integer.MAX_VALUE;
                return oldTab;
            }
            //扩容为原来的两倍 
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                     oldCap >= DEFAULT_INITIAL_CAPACITY)
                newThr = oldThr << 1; //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;
        //将原本的node重新分到新的hashmap中
        if (oldTab != null) {
            //遍历bucket数组
            for (int j = 0; j < oldCap; ++j) {
                Node<K,V> e;
                if ((e = oldTab[j]) != null) {
                    //释放原本的空间
                    oldTab[j] = null;
                    //如果next节点为空
                    if (e.next == null)
                        //重新hash,并放入相应的位置
                        newTab[e.hash & (newCap - 1)] = e;
                    //如果是红黑树的根节点
                    else if (e instanceof TreeNode)
                        //拆树
                        ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
                    //next节点不为空
                    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;
                            //为0表明(e.hash & (newCap - 1))还会和 e.hash & (oldCap - 1)一                                    
                            //样,即该节点所处索引不变,即在新map的未扩容之前的部分 low链表中
                            //因为扩容一次,原本的链表最多会成为两个链表,一个在原来的索引下    
                            //(low链表)一个在扩容后大一点的索引中(high链表)。这样扩容时构造链 
                            //表的效率很高,而且不会产生循环链表
                            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.8下,resize操作维护了两个链表,每次在尾部插入节点;在多线程下也不会造成环形链表

猜你喜欢

转载自blog.csdn.net/fendianli6830/article/details/81102709