Java HashMap源码阅读


    final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {

        HashMap.Node<K,V>[] tab; HashMap.Node<K,V> p; int n, i;
        // 如果table为空,则resize(),初始化n,n=16;
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        //如果当前table中没有值,则创建新的Node
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        //否则更新已有Key的值
        else {
            HashMap.Node<K,V> e; K k;
            //如果当前Key和p相等,则e = p;
            if (p.hash == hash &&
                    ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
            //如果是一个TreeNode,则调用preeVal插入
            else if (p instanceof HashMap.TreeNode)
                e = ((HashMap.TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            //如果不是TreeNode且不和当前的Hash值相等的Key相等
            else {
                //顺着链表往后插
                for (int binCount = 0; ; ++binCount) {
                    //e = p.next
                    if ((e = p.next) == null) {
                        p.next = newNode(hash, key, value, null);
                        //如果链表长度大于规定的长度,则插入红黑树
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            treeifyBin(tab, hash);
                        break;
                    }
                    //如果在链表中找到了Hash值相等且equals的值则break;
                    if (e.hash == hash &&
                            ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e;
                }
            }
            //如果该Key存在于HashMap中则返回旧的值
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        //修改次数加1,size+1,然后判断当前size是否大于阈值,如果大于则resie();
        ++modCount;
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }
final HashMap.Node<K,V>[] resize() {
        HashMap.Node<K,V>[] oldTab = table;
        //如果当前table为空,则oldCap = 0,否则 oldCap = table.length;
        int oldCap = (oldTab == null) ? 0 : oldTab.length;
        int oldThr = threshold;
        int newCap, newThr = 0;
        if (oldCap > 0) {
            //如果旧的长度>=MAXIMUM_CAPACITY,则让阈值变为Integer.MAX_VALUE
            if (oldCap >= MAXIMUM_CAPACITY) {
                threshold = Integer.MAX_VALUE;
                return oldTab;
            }
            //否则,容量变为原来的2倍,阈值也变为原来的2倍
            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"})
        HashMap.Node<K,V>[] newTab = (HashMap.Node<K,V>[])new HashMap.Node[newCap];
        table = newTab;
        if (oldTab != null) {
            //遍历旧的table
            for (int j = 0; j < oldCap; ++j) {
                HashMap.Node<K,V> e;
                //如果table[j]!=null
                if ((e = oldTab[j]) != null) {
                    //先将oldTab[j]置为null
                    oldTab[j] = null;
                    //如果没有Hash冲突,也就是该Node存储在数组中,则将该节点放到再hash里面的数组中
                    if (e.next == null)
                        newTab[e.hash & (newCap - 1)] = e;
                    //如果该节点是一个TreeNode
                    else if (e instanceof HashMap.TreeNode)
                        ((HashMap.TreeNode<K,V>)e).split(this, newTab, j, oldCap);
                    //否则,也就是存在hash冲突,该节点后面有链表
                    else { // preserve order
                        HashMap.Node<K,V> loHead = null, loTail = null;
                        HashMap.Node<K,V> hiHead = null, hiTail = null;
                        HashMap.Node<K,V> next;
                        do {
                            next = e.next;
                            //尾插法可以避免JDK7中的头插法在多线程中产生的链表死循环的问题,但是仍未解决多线程下数据丢失问题
                            //尾插法新建链表 table.size()也就是hash值范围,hash值范围在[0,oldCap-1]之间
                            //eg:oldCap = 1000,最大Hash值为111.
                            //那么,如果当前Hash值为111&1000==0
                            //如果当前Hash值为1010&1000!=0
                            //如果当前的Hash和高为做&运算为0,则loHead为e,然后一直遍历e链表。
                            if ((e.hash & oldCap) == 0) {
                                if (loTail == null)
                                    loHead = e;
                                else
                                    loTail.next = e;
                                loTail = e;
                            }
                            //否则,也就是当前hash值在高为有不为0
                            else {
                                if (hiTail == null)
                                    hiHead = e;
                                else
                                    hiTail.next = e;
                                hiTail = e;
                            }
                        } while ((e = next) != null);
                        //Hash值不变,直接插入数组中。
                        if (loTail != null) {
                            loTail.next = null;
                            newTab[j] = loHead;
                        }
                        //eg:1010&1000!=0,则应该插入,[8+j]处
                        //否则,插入到[oldCap+j]的位置处。
                        if (hiTail != null) {
                            hiTail.next = null;
                            newTab[j + oldCap] = hiHead;
                        }
                    }
                }
            }
        }
        return newTab;
    }
final HashMap.Node<K,V> removeNode(int hash, Object key, Object value,
                                       boolean matchValue, boolean movable) {
        HashMap.Node<K,V>[] tab; HashMap.Node<K,V> p; int n, index;
        if ((tab = table) != null && (n = tab.length) > 0 &&
                (p = tab[index = (n - 1) & hash]) != null) {
            HashMap.Node<K,V> node = null, e; K k; V v;
            //如果p在table数组中,node = p;
            if (p.hash == hash &&
                    ((k = p.key) == key || (key != null && key.equals(k))))
                node = p;
            
            //否则,遍历链表
            else if ((e = p.next) != null) {
                //如果是一个TreeNode,则调用getTreeNode获取节点
                if (p instanceof HashMap.TreeNode)
                    node = ((HashMap.TreeNode<K,V>)p).getTreeNode(hash, key);
                //否则,是一个链表中的节点,遍历链表,直到找到相等的Node。
                else {
                    do {
                        if (e.hash == hash &&
                                ((k = e.key) == key ||
                                        (key != null && key.equals(k)))) {
                            node = e;
                            break;
                        }
                        p = e;
                    } while ((e = e.next) != null);
                }
            }
            //如果找到了node
            if (node != null && (!matchValue || (v = node.value) == value ||
                    (value != null && value.equals(v)))) {
                //如果是一个TreeNode,则调用removeTreeNode删除节点
                if (node instanceof HashMap.TreeNode)
                    ((HashMap.TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
                //如果是在数组中的节点,则直接将当前node的next放入数组中
                else if (node == p)
                    tab[index] = node.next;
                //如果是链表中的节点,则当前删除node是通过改变node上一个节点的next,将p->node-node.next改为p->node.next删除node
                else
                    p.next = node.next;
                //将修改次数加一
                ++modCount;
                //将当前hashMap的size-1
                --size;
                afterNodeRemoval(node);
                return node;
            }
        }
        return null;
    }

猜你喜欢

转载自blog.csdn.net/qq_23128065/article/details/105108303