5)compute(K key,BiFunction<? super K, ? super V, ? extends V> remappingFunction);//根据已知的 k v 算出新的v并put
/** * 根据已知的 k v 算出新的v并put。 * 如果根据key获取的oldVal为空则lambda中涉及到oldVal的计算会报空指针。 * 如:map.compute("a", (key, oldVal) -> oldVal + 1); 如果oldVal为null,则空指针 * 源码和merge类似 * BiFunction返回值作为新的value,BiFunction有二个参数 * @param key * @param remappingFunction * @return */ @Override public V compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) { 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; 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 = (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); } } V oldValue = (old == null) ? null : old.value; V v = remappingFunction.apply(key, oldValue); if (old != null) { if (v != null) { old.value = v; afterNodeAccess(old); } else removeNode(hash, key, null, false, true); } else if (v != null) { if (t != null) t.putTreeVal(this, tab, hash, key, v); else { tab[i] = newNode(hash, key, v, first); if (binCount >= TREEIFY_THRESHOLD - 1) treeifyBin(tab, hash); } ++modCount; ++size; afterNodeInsertion(true); } return v; }HashMap源码分析--jdk1.8 (5)
内容版权声明:除非注明,否则皆为本站原创文章。