JDK8 中 HashMap put 方法源码理解(近期整理,待完善)

HashMap

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 <tt>key</tt>, or
  *         <tt>null</tt> if there was no mapping for <tt>key</tt>.
  *         (A <tt>null</tt> return can also indicate that the map
  *         previously associated <tt>null</tt> with <tt>key</tt>.)
  */
 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) {
    Node<K,V>[] tab; Node<K,V> p; int n, i;
    // 如果table是null或者长度为0,则创建一个新table并且得到其length
    if ((tab = table) == null || (n = tab.length) == 0) {
        n = (tab = resize()).length;
    }
    // 根据键值的hash&(n-1)得到插入的table的索引i
    // 若tab[i]上没有节点,则新建节点并将此KV对添加进来
    if ((p = tab[i = (n - 1) & hash]) == null) {
        tab[i] = newNode(hash, key, value, null);   
    } else {// 如果此位置上已存在节点
        Node<K,V> e; K k;
        if (p.hash == hash && 
            ((k = p.key) == key || (key != null && key.equals(k)))) {
            // 判断table[i]的首个元素的key和待put元素的key是否相同
            // 若相同,直接执行existing mapping for key这行代码
            e = p;// 当前table[i]的首个元素先保存在内存中
        } else if (p instanceof TreeNode) {
            // 判断table[i]是否为TreeNode(红黑树),若是,则直接在树中插入键值对
            e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
        } else { // 链表数据结构(非红黑树)
            // 遍历table[i],判断链表长度是否大于TREEIFY_THRESHOLD(默认值为8)
            // 大于8的话把链表转换为红黑树,在红黑树中执行插入操作,否则进行链表的插入操作
            // 遍历过程中若发现key已经存在,直接(break)覆盖value
            for (int binCount = 0; ; ++binCount) {
                if ((e = p.next) == null) {
                    p.next = newNode(hash, key, value, null);
                    if (binCount >= TREEIFY_THRESHOLD - 1) { // -1 for 1st
                        treeifyBin(tab, hash);
                    }
                    break;// 强制结束,跳出for循环,执行existing mapping for key这行代码
                }
                if (e.hash == hash &&
                    ((k = e.key) == key || (key != null && key.equals(k)))) {
                        break;// key相同,跳出循环,执行existing mapping for key这行代码
                    }
                p = e;
            }
        }
        if (e != null) { // existing mapping for key
            // key相同,保留旧key,更新value,并返回旧value
            V oldValue = e.value;
            if (!onlyIfAbsent || oldValue == null){
                e.value = value;
            }
            afterNodeAccess(e);
            return oldValue;
        }
    }
    ++modCount;
    // 插入成功后,判断实际存在的键值对数量size是否超多了最大容量threshold,如果超过,进行扩容
    if (++size > threshold) {
        resize();
    }
    afterNodeInsertion(evict);
    return null;// table[i]上没有节点的情况下,返回null
}

测试:

package com.ggsddu.domain;

import javax.xml.soap.Node;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class TestSB {
    public static void main(String[] args) {
        Map<String, Object> map = new HashMap<>();

        Object one = map.put("one", 1);
        Object two = map.put("two", 2);
        System.out.println(one);
        System.out.println(two);

        // 测试:插入重复的key
        Object t = map.put("two", 3);
        System.out.println(t);

        System.out.println(map.toString());
    }
}

控制台:

null
null
2
{one=1, two=3}

Process finished with exit code 0
发布了44 篇原创文章 · 获赞 42 · 访问量 21万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览