HashMap源码分析--jdk1.8 (4)

     3)V putIfAbsent(K key, V value);//如果key存在,则跳过,不覆盖value值,onlyIfAbsent传true,不覆盖更改现有值

/** * 如果key存在则跳过,不覆盖value值,onlyIfAbsent传true,不覆盖更改现有值 * 如果key不存在则put * @param key * @param value * @return */ @Override public V putIfAbsent(K key, V value) { return putVal(hash(key), key, value, true, true); }

     4)merge(K key, V value,BiFunction<? super V, ? super V, ? extends V> remappingFunction);//用某种方法更新原来的value值

/** * 用某种方法更新原来的value值 * BiFunction支持函数式变成,lambda表达式,如:String::concat拼接 * @param key * @param value * @param remappingFunction * @return */ @Override public V merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction) { if (value == null) throw new NullPointerException(); if (remappingFunction == null) throw new NullPointerException(); int hash = hash(key); Node<K,V>[] tab; Node<K,V> first; int n, i; int binCount = 0; TreeNode<K,V> t = null; Node<K,V> old = null;// 该key原来的节点对象 if (size > threshold || (tab = table) == null || (n = tab.length) == 0)//判断是否需要扩容 n = (tab = resize()).length; if ((first = tab[i = (n - 1) & hash]) != null) { if (first instanceof TreeNode)// 取出old Node对象 old = (t = (TreeNode<K,V>)first).getTreeNode(hash, key); else { Node<K,V> e = first; K k; do { if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) { old = e; break; } ++binCount; } while ((e = e.next) != null); } } if (old != null) {//如果 old Node 存在 V v; if (old.value != null) // 如果old存在,执行lambda,算出新的val并写入old Node后返回。 v = remappingFunction.apply(old.value, value); else v = value; if (v != null) { old.value = v; afterNodeAccess(old); } else removeNode(hash, key, null, false, true); return v; } if (value != null) { //如果old不存在且传入的newVal不为null,则put新的kv if (t != null) t.putTreeVal(this, tab, hash, key, value); else { tab[i] = newNode(hash, key, value, first); if (binCount >= TREEIFY_THRESHOLD - 1) treeifyBin(tab, hash); } ++modCount; ++size; afterNodeInsertion(true); } return value; }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zyssgd.html