computeIfAbsent()方法会在执行时查询table是否存在指定的key,
if (mappingFunction == null)
throw new NullPointerException();
int hash = hash(key); // 获取key的hash值
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 || // 判断table是否需要扩容
(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)))) { // key和hash都相等,表示存在相同的节点,则调用该节点
old = e;
break;
}
++binCount;
} while ((e = e.next) != null);
}
V oldValue;
if (old != null && (oldValue = old.value) != null) { // 如果节点不为null,或者节点的value不为null,就返回value值
afterNodeAccess(old);
return oldValue;
}
}
V v = mappingFunction.apply(key); // 调用函数
if (v == null) { // value为null,则返回null
return null;
} else if (old != null) { // 如果就节点不为null,则覆盖旧值
old.value = v;
afterNodeAccess(old);
return v;
}
else if (t != null) // 红黑树操作
t.putTreeVal(this, tab, hash, key, v);
else { //
tab[i] = newNode(hash, key, v, first); // 新建节点,并存放在hash下标中
if (binCount >= TREEIFY_THRESHOLD - 1) // 链表超过8个,则转换为红黑树
treeifyBin(tab, hash);
}
++modCount;
++size;
afterNodeInsertion(true);
return v;
}
如果存在,返回value值
如果不存在,则执行mappingFunction.apply(key)方法,查询value值,添加进map,并返回查询的value值,
但是mappingFunction.apply((key)返回的值为null或抛出异常,则不会添加进map
if (mappingFunction == null)
throw new NullPointerException();
int hash = hash(key); // 获取key的hash值
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 || // 判断table是否需要扩容
(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)))) { // key和hash都相等,表示存在相同的节点,则调用该节点
old = e;
break;
}
++binCount;
} while ((e = e.next) != null);
}
V oldValue;
if (old != null && (oldValue = old.value) != null) { // 如果节点不为null,或者节点的value不为null,就返回value值
afterNodeAccess(old);
return oldValue;
}
}
V v = mappingFunction.apply(key); // 调用函数
if (v == null) { // value为null,则返回null
return null;
} else if (old != null) { // 如果就节点不为null,则覆盖旧值
old.value = v;
afterNodeAccess(old);
return v;
}
else if (t != null) // 红黑树操作
t.putTreeVal(this, tab, hash, key, v);
else { //
tab[i] = newNode(hash, key, v, first); // 新建节点,并存放在hash下标中
if (binCount >= TREEIFY_THRESHOLD - 1) // 链表超过8个,则转换为红黑树
treeifyBin(tab, hash);
}
++modCount;
++size;
afterNodeInsertion(true);
return v;
}