HashMap put方法的源码分析

背景知识:

java1.7 HashMap用的是数组+链表实现的,同时采用的头插入法,存在死循环的问题

java1.8 HashMap用的是数组+链表+红黑树实现的,采用尾插法实现的,解决了死循环的问题,今天分析的就是1.8

    // 初始容量为16
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16    

    // 默认负载因子    
    static final float DEFAULT_LOAD_FACTOR = 0.75f;

    // 默认临界值
    static final int TREEIFY_THRESHOLD = 8;

    // 此为为我们调用的put方法
    public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }
   
    // 获取key对应的hash值的方法
    static final int hash(Object key) {
        int h;
        // 此处可以看出,hashmap会把为null的key方法数组下标为0的位置上
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }

     /**
     * Implements Map.put and related methods.
     *
     * @param  key的hash值
     * @param  key
     * @param  key对应的value
     * @param  默认flase,会覆盖相同key的value值
     * @param  默认true,初始化不调用此方法
     * @return previous value, or null if none
     */
    final V putVal(int hash, K key, V value, boolean onlyIfAbsent,boolean evict) {
        // tab为数组,p为链表的临时节点,n为数组的长度,i为key对应的数组index
        Node<K,V>[] tab; Node<K,V> p; int n, i;
        // 判断数组是否为空,直接扩容
        if ((tab = table) == null || (n = tab.length) == 0){
            n = (tab = resize()).length;
        }
        // 根绝key的hash值获取,key对应的数组下标,如果该下标中,数组没有值,则直接放进去
        if ((p = tab[i = (n - 1) & hash]) == null){
            tab[i] = newNode(hash, key, value, null);
        }
        // 否则发生了hash冲突(就是根据放入的key的hash值算出下标位置,在数组中已经存有数据了)
        else {
            // 新实例化一个node节点,用于暂存数据
            Node<K,V> e; K k;
            // hash值和key的都相等,则覆盖此key的value值
            if (p.hash == hash &&((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
            // 如果此时,p为树节点,则将红黑树中key对应的节点取出来,给e
            // instancesof() 判断左边的是否属于右边的类
            else if (p instanceof TreeNode)
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            // 此时为同一个数组下标,但是key值不等
            else {
                // 遍历链表
                for (int binCount = 0; ; ++binCount) {
                    if ((e = p.next) == null) {
                        // 遍历到链表尾部,添加新的节点
                        p.next = newNode(hash, key, value, null);
                        // 添加新的节点之后,如果链表长度 > 8,则转换为红黑树
                        if (binCount >= TREEIFY_THRESHOLD - 1) 
                            treeifyBin(tab, hash);
                        break;
                    }
                    // 找到要覆盖的节点,直接跳出遍历
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e;
                }
            }
            // 如果此时e不为空,则说明,此key在hashmap中已经存在,进行覆盖操作
            if (e != null) { 
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)              
                    e.value = value;
                afterNodeAccess(e);
                // 返回旧value
                return oldValue;
            }
        }
        // 记录hashmap变化的次数
        ++modCount;

        // 如果数组的长度大于临界值,则hashmap的数组进行扩容
        if (++size > threshold)
            resize();
        // 这是一个空实现的函数,用作LinkedHashMap重写使用。
        afterNodeInsertion(evict);
        return null;
    }
发布了219 篇原创文章 · 获赞 292 · 访问量 10万+

猜你喜欢

转载自blog.csdn.net/lk1822791193/article/details/104789153