HashMap_put方法实现解析

HashMap底层实现解析,使用的是jdk14

1 hashmap 内部节点(内部类)

    /**
     * Basic hash bin node, used for most entries.  (See below for
     * TreeNode subclass, and in LinkedHashMap for its Entry subclass.)
     */
    static class Node<K,V> implements Map.Entry<K,V> {
        final int hash;
        final K key;
        V value;
        Node<K,V> next;

        Node(int hash, K key, V value, Node<K,V> next) {
            this.hash = hash;
            this.key = key;
            this.value = value;
            this.next = next;
        }

        public final K getKey()        { return key; }
        public final V getValue()      { return value; }
        public final String toString() { return key + "=" + value; }

        public final int hashCode() {
            return Objects.hashCode(key) ^ Objects.hashCode(value);
        }

        public final V setValue(V newValue) {
            V oldValue = value;
            value = newValue;
            return oldValue;
        }

        public final boolean equals(Object o) {
            if (o == this)
                return true;
            if (o instanceof Map.Entry) {
                Map.Entry<?,?> e = (Map.Entry<?,?>)o;
                if (Objects.equals(key, e.getKey()) &&
                    Objects.equals(value, e.getValue()))
                    return true;
            }
            return false;
        }
    }

2 put方法

    /**
     * Associates the specified value with the specified key in this map.
     * If the map previously contained a mapping for the key, the old
     * value is replaced.
     *
     * @param key key with which the specified value is to be associated
     * @param value value to be associated with the specified key
     * @return the previous value associated with {@code key}, or
     *         {@code null} if there was no mapping for {@code key}.
     *         (A {@code null} return can also indicate that the map
     *         previously associated {@code null} with {@code key}.)
     */
    public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }

    /**
     * Implements Map.put and related methods.
     *
     * @param hash hash for key
     * @param key the key
     * @param value the value to put
     * @param onlyIfAbsent if true, don't change existing value
     * @param evict if false, the table is in creation mode.
     * @return previous value, or null if none
     */
    final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
                   
		// tab 数组加链表;
		// p 链表
		// n 数组总长度
		// i 链表在数组中的定位下标
        Node<K,V>[] tab; Node<K,V> p; int n, i;
        
        // tab = table 初始化数组加链表
        // n = tab.length 初始化链表长度
		// 如果数组为空或数组长度为0
        if ((tab = table) == null || (n = tab.length) == 0)
        	// 重新赋值数组的长度
            n = (tab = resize()).length;
            
        
        // i = (n - 1) & hash 获取节点所在筒的定位下标
        // p = tab[i] 获取该下标指定的筒(链表)
        // 如果获取不到节点所在的筒
        if ((p = tab[i = (n - 1) & hash]) == null)
        
        	// 新建筒
        	// 并赋值给下标为i的筒
            tab[i] = newNode(hash, key, value, null);
            
        else {
			// e 创建一个新的链表对象
			// k 创建一个新的健对象
            Node<K,V> e; K k;
            
            // k = p.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 {
            	// int binCount 节点数量统计值
            	// 遍历筒下面的所有节点
                for (int binCount = 0; ; ++binCount) {

					// e = p.next 获取节点的下个节点
					// 下一个节点为空
                    if ((e = p.next) == null) {
                    
                    	// 用新增数据创建新的节点
                    	// 赋值给下一个节点
                        p.next = newNode(hash, key, value, null);

						// 节点梳理超过数据结构转化(链表转红黑树)的阈值
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                        	// 转化当前筒的链表数据结构为红黑树结构
                            treeifyBin(tab, hash);
                        // 结束遍历
                        break;
                    }
					
					// k = e.key 获取节点的key
					// 如果筒存在,并且节点也存在
                    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;

				// !onlyIfAbsent 必定为true
                if (!onlyIfAbsent || oldValue == null)
                	// 给节点的值赋值新值
                    e.value = value;

				// 将节点移到筒的足后位置
                afterNodeAccess(e);
                // 返回就的节点的值;
                return oldValue;
            }
        }

		// 数据结构变化统计值,自增1
        ++modCount;

		// 健值对数量,自增1
		// 健值对数量超过hashmap扩容的阈值
        if (++size > threshold)
			// hashMap扩容
			// 重整hashmap数据
            resize();

		// 修改节点值
        afterNodeInsertion(evict);
        return null;
    }

猜你喜欢

转载自blog.csdn.net/leinminna/article/details/106145418