HashMap-putVal方法浅析

HashMap中的putVal方法:插入一个新的键值对,如果该键存在,则用新值覆盖旧值,方法返回值为旧值,如果该键不存在,方法返回值为null。



  • putValue方法源码及分析如下:
    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)
        	//初始化操作
            n = (tab = resize()).length;
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {
            Node<K,V> e; K k;
            // 如果新插入结点和table中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 {
            	//往后遍历当前链表
                for (int binCount = 0; ; ++binCount) {
                	//判断如果链表只有一个头节点,则以尾插法在链表尾部插入一个新的节点
                    if ((e = p.next) == null) {                    	
                        p.next = newNode(hash, key, value, null);
                        //判断如果链表长度大于阈值8,将链表转为红黑树
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            treeifyBin(tab, hash);
                        break;
                    }
                    //如果新插入结点和e结点(p.next)的hash值,key值相同,直接跳出for循环
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e;
                }
            }
            //找到key值相等的节点,考虑新值覆盖旧值
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                //判断是否允许覆盖,value是否为空
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                //回调以允许LinkedHashMap后置操作
                afterNodeAccess(e);
                return oldValue;
            }
        }
        //modCount为操作次数
        ++modCount;
        //判断如果size大于阈值,进行数组扩容
        if (++size > threshold)
            resize();
        //回调以允许LinkedHashMap后置操作
        afterNodeInsertion(evict);
        return null;
    }



  • 简易程序流程图如下:
    HashMap的Put操作流程图

版权声明:本文为Roy_396原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。