HashMap put 办法解析
jdk1.8中,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); }复制代码
putVal办法传入参数
hash(key):将要寄存的key进行hash运算
static final int hash(Object key) { int h; return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);}复制代码
- key: 寄存的key
- value:寄存的值
- onlyIfAbsent:如果为true,不扭转已存在的value值,就是当将要存的key与map中的key雷同时,不必新值替换久值
- evict:如果为false,示意处于创立模式
putVal 源码
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 定义 transient Node<K,V>[] table; // tab = table 将table 赋值给tab 并判断是否为空,tab.length赋值给n,判断长度 if ((tab = table) == null || (n = tab.length) == 0) // 调用resize办法,从新计算容量,并把长度给n n = (tab = resize()).length; // 判断在 tab在 (n - 1) & hash 有不有值,没有值就间接将要寄存的数据放进去 if ((p = tab[i = (n - 1) & hash]) == null) tab[i] = newNode(hash, key, value, null); else { // 否则,可能是有hash抵触了,须要断定了 Node<K,V> e; K k; // 这里通过旧数据的 hash值与将要存入的hash值,以及key值比照,如果是一样的,将map外面这个元素赋值给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 { // 如果又不抵触,又不是树结构,则开始遍历,这是一个死循环,必须通过break退出 for (int binCount = 0; ; ++binCount) { // 找到链表的尾部,将数据直接插入链表尾部(尾插法) if ((e = p.next) == null) { p.next = newNode(hash, key, value, null); // 请留神,当数组的大小>=7的时候,hashmap会转换为红黑树结构,然而不是肯定会转,treeifyBin办法会判断 // if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY) resize(); // 当传入的 tab 为空或者 hash tab的长度小于 (MIN_TREEIFY_CAPACITY=64)时,它其实只会扩容,并不会转换为红黑树 if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st treeifyBin(tab, hash); break; } 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; if (!onlyIfAbsent || oldValue == null) e.value = value; afterNodeAccess(e); return oldValue; } } // modCount 示意这个hashmap构造批改的次数,用于迭代器应用 ++modCount; // size map中的key-value 个数 // threshold 示意下一次进行扩容的大小,它是由 (capacity * load factor) 计算出来的 if (++size > threshold) resize(); afterNodeInsertion(evict); return null;}
参考:《2020最新Java根底精讲视频教程和学习路线!》
链接:https://juejin.cn/post/693869...