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> {

		// 节点key 的hash值
        final int hash;
        // 节点的key是final 类型,不允许修改key
        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; }

		// 重写的hashCode方法
        public final int hashCode() {
            return Objects.hashCode(key) ^ Objects.hashCode(value);
        }

		// 设置节点的值,返回节点的老的值
        public final V setValue(V newValue) {
            V oldValue = value;
            value = newValue;
            return oldValue;
        }

		// 重写equals方法 
        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()))
                    // 返回true
                    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;
    }

3 相关的其他方法

// 重整hashmap数据
resize();
// 用新增数据创建新的节点
newNode(hash, key, value, null);
// 把节点值放入树中
((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
// 将节点移到筒的最后位置
afterNodeAccess(e);
// 转化当前筒的链表数据结构为红黑树结构
treeifyBin(tab, hash);
// 修改节点值
afterNodeInsertion(evict);
3.1 resize()

    /**
     * 调整数组数据结构
     * 数组为空,按照数组的初始化长度初始化数组,
     * 不为空,加倍扩容原数组长度(筒的数量),index 做相应调整(筒的定位下标)
     * Initializes or doubles table size.  If null, allocates in
     * accord with initial capacity target held in field threshold.
     * Otherwise, because we are using power-of-two expansion, the
     * elements from each bin must either stay at same index, or move
     * with a power of two offset in the new table.
     *
     * @return the table
     */
    final Node<K,V>[] resize() {

		// 获取原来的数组加链表
        Node<K,V>[] oldTab = table;

		// 获取老数组的长度,筒的数量
        int oldCap = (oldTab == null) ? 0 : oldTab.length;

		// 获取老数组的扩容阈值
        int oldThr = threshold;

		// 初始化
		// newCap 新数组的数组长度
		//  newThr 新数组的扩容阈值
        int newCap, newThr = 0;

		// 如果老数组长度大于0
        if (oldCap > 0) {
        	// MAXIMUM_CAPACITY hashmap 数组的最大容量。1<<30。
        	// 如果老数组的长度大于等于hashmap 数组最大容量
            if (oldCap >= MAXIMUM_CAPACITY) {

				//  Integer.MAX_VALUE = 2<<31-1
				// 给hashmap实际最大容量容赋值
                threshold = Integer.MAX_VALUE;
                // 返回原来的数组加链表
                return oldTab;
            }

			// newCap = oldCap << 1 新数组扩容为老数组的两倍;
			// MAXIMUM_CAPACITY hashmap 数组的最大容量。1<<30。
			// DEFAULT_INITIAL_CAPACITY hashmap数组的默认长度,16
			// 如果新数组长度小于hashmap最大容量,并且,老数组的长度大于等于16
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                     oldCap >= DEFAULT_INITIAL_CAPACITY)
                     
                // 新数组的阔容阈值赋值维老数组扩容阈值的两倍
                newThr = oldThr << 1; // double threshold
        }

		// 如果老数组的扩容阈值大于0
        else if (oldThr > 0) // initial capacity was placed in threshold
            // 新数组容量变为老数组的扩容阈值
            newCap = oldThr;

		// 数组初始长度标记为0
        else {               // zero initial threshold signifies using defaults
            
            // 设置新数组的长为默认长度16;
            newCap = DEFAULT_INITIAL_CAPACITY;
            // 设置新数组的扩容阈值为,0.75*16 = 12,即,数组的长度为大于等于12时,数组再次扩容
            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
        }

		// 如果新数组的扩容阈值没有设置
        if (newThr == 0) {
        	// 通过新数组的容量和负载因子计算得到计算值;
            float ft = (float)newCap * loadFactor;
            // 如果新数组的容量小于最大极限容量,并且,计算值小于最大极限容量,那么新数组的容量设置为计算值,否则设置为极限容量
            newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
                      (int)ft : Integer.MAX_VALUE);
        }

		// 
        threshold = newThr;
        @SuppressWarnings({"rawtypes","unchecked"})
            Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
        table = newTab;
        if (oldTab != null) {
            for (int j = 0; j < oldCap; ++j) {
                Node<K,V> e;
                if ((e = oldTab[j]) != null) {
                    oldTab[j] = null;
                    if (e.next == null)
                        newTab[e.hash & (newCap - 1)] = e;
                    else if (e instanceof TreeNode)
                        ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
                    else { // preserve order
                        Node<K,V> loHead = null, loTail = null;
                        Node<K,V> hiHead = null, hiTail = null;
                        Node<K,V> next;
                        do {
                            next = e.next;
                            if ((e.hash & oldCap) == 0) {
                                if (loTail == null)
                                    loHead = e;
                                else
                                    loTail.next = e;
                                loTail = e;
                            }
                            else {
                                if (hiTail == null)
                                    hiHead = e;
                                else
                                    hiTail.next = e;
                                hiTail = e;
                            }
                        } while ((e = next) != null);
                        if (loTail != null) {
                            loTail.next = null;
                            newTab[j] = loHead;
                        }
                        if (hiTail != null) {
                            hiTail.next = null;
                            newTab[j + oldCap] = hiHead;
                        }
                    }
                }
            }
        }
        return newTab;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值