(java 8)hashMap-putVal()解读

 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)
        // 当前table容量为0,会进行一次resize(),这个里面还会根据tab.length进行判断
            n = (tab = resize()).length;
        if ((p = tab[i = (n - 1) & hash]) == null)
        // hash到的数组位置的第一个node为null,直接添加到第一个位置
            tab[i] = newNode(hash, key, value, null);
        else {
            Node<K,V> e; K k;
            // p已经在if中赋值了,所有接下来判断p的 hash和key 与当前要添加的数据的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 {
                for (int binCount = 0; ; ++binCount) {
                // 遍历到了链表尾部,没有发现存在相同key的节点,则添加到链表尾部,当然是在没有满足红黑树变化阈值的前提下
                    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;
                 // put 的时候 onlyIfAbsent是false 会改变已经存在的值
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                // hashMap 的 afterNodeAccess是个空函数,LinkedHashMap会实现该函数
                afterNodeAccess(e);
                // 返回的是旧值
                return oldValue;
            }
        }
        // 新增数据时,modCount和size加1,并且超过阈值负载,会进行resize
        ++modCount;
        if (++size > threshold)
            resize();
        // 节点新增之后的处理.比如 LinkedHashMap会实现该函数,会移除最老的数据
        afterNodeInsertion(evict);
        return null;
    }

 总结:

1.当前table容量为0,会进行一次resize()

2.put方法是覆盖旧值的,通过比较hash值 == 和 equals进行判断

3.新增元素从链表的是加入到尾部,hashMap中还有一个merge方法,该方法当节点不存在时,是将新的节点增加到链表的头部的,可以去看看源码

4.当链表的元素超过或者等于8时,尝试进行红黑树,注意这里是尝试,正在要转换树,还有另外一个条件:tab的size大于64。

5.新增数据时,modCount和size加1,并且超过阈值负载,会进行resize

6.节点新增之后的处理.比如 LinkedHashMap会实现该afterNodeInsertion函数,会移除最老的数据

posted @ 2019-12-31 14:53  Enast  阅读(527)  评论(0编辑  收藏  举报