阅读JDK1.8版本HashMap的put方法源码

final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
               boolean evict) {
    Node<K,V>[] tab; //当前数组
    Node<K,V> p; // 当前i位置上的元素
    int n; //tab总长度
    int i; //当前元素要存放的数组位置,由数组长度 & hash算出
    // 将table赋给tab,如果table == null,或者,tab是一个空数组
    if ((tab = table) == null || (n = tab.length) == 0)
        //调用resize创建或扩容数组,赋值给tab,并返回长度赋值给n
        n = (tab = resize()).length;
    /* 用数组最大角标(n-1) & hash,计算出hash在数组的下标位置,赋给i
     * 从tab中取得此值,赋p,判断是否为空
     */
    if ((p = tab[i = (n - 1) & hash]) == null)
        //创建此节点放入数组
        tab[i] = newNode(hash, key, value, null);
    else {
        //tab的i位置元素不为空
        Node<K,V> e; // 当前key-value存放的节点
        K k; // p节点的key元素
        //p节点的hash相同,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 {
            // binCount 可以理解为当前Node的链表长度,从0开始,每次+1
            for (int binCount = 0; ; ++binCount) {
                //将当前数组下标i上p值的next赋给e,如果next没有值
                if ((e = p.next) == null) {
                    // 新增节点,然后赋给p.next
                    p.next = newNode(hash, key, value, null);
                    // 如果长度 >= 临界值 7(8-1),转为红黑树
                    if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                        treeifyBin(tab, hash);
                    break;//跳出循环
                }
                //如果p.next 不等于null,判断key value是否都相同,跳出循环
                if (e.hash == hash &&
                    ((k = e.key) == key || (key != null && key.equals(k))))
                    break;
               //如果p.next 不等于null,key value不相同,就把e(p.next)赋给p继续循环遍历
                p = e;
            }
        }
        //如果e != null,将value放到e内,并返回e节点原来的value
        if (e != null) {
            V oldValue = e.value;
            // e.value 赋值,并返回老的value
            if (!onlyIfAbsent || oldValue == null)
                e.value = value;
            afterNodeAccess(e);
            return oldValue;
        }
    }
    ++modCount;// 增加modifications总数
    // 元素数 > 临界值,就重新扩展数组
    if (++size > threshold)
        resize();
    afterNodeInsertion(evict);
    return null;
}
原文地址:https://www.cnblogs.com/inkyi/p/14510096.html