HashMap源码

98 阅读2分钟

put源码


final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
               boolean evict) {
    Node<K,V>[] tab; Node<K,V> p; int n, i;
    //第一次执行put,才为hashmap分配空间
    if ((tab = table) == null || (n = tab.length) == 0)
        n = (tab = resize()).length;
       // 插入的key在数组的下标值 i=(n-1)&hash 如果tab[i]==null,直接插入
    if ((p = tab[i = (n - 1) & hash]) == null)
        tab[i] = newNode(hash, key, value, null);
    else { // 如果tab[i]!=null,则向链表或红黑树中插入
        Node<K,V> e; K k;
        //判断对应数组上的元素的key与插入的key相等,相等则代替。
        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;//记录map的结构性修改
    //当map的键值对大于阈值,则扩容
    if (++size > threshold)
        resize();
    afterNodeInsertion(evict);
    return null;
}

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;
    // 容量扩展的两种情况:旧容量已经达到最大值,就不扩容了,如果没达到,就扩大 1 倍。
    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
    }
    // 此处代表map尚未初始化(因为容量小于0),故此这两个else都是为新map初始化
    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;
                        // 满足e.hash&oldCap=0的元素,其在新旧数组中的索引位置不变
                        if ((e.hash & oldCap) == 0) {
                            if (loTail == null)
                                loHead = e;
                            else
                                loTail.next = e;
                            loTail = e;
                        }
                        // e.hash&oldCap不等于0的元素,其在新数组中的索引位置是其在旧数组中索引位置的基础上再加上旧数组长度个偏移量
                        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;
}