文章目录

这个是Java8里面新增的功能

代码:

public V computeIfAbsent(K key,
                         Function<? super K, ? extends V> mappingFunction) {
    if (mappingFunction == 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;
        if (old != null && (oldValue = old.value) != null) {
            afterNodeAccess(old);
            return oldValue;
        }
    }
    V v = mappingFunction.apply(key);
    if (v == null) {
        return null;
    } else if (old != 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);
        if (binCount >= TREEIFY_THRESHOLD - 1)
            treeifyBin(tab, hash);
    }
    ++modCount;
    ++size;
    afterNodeInsertion(true);
    return v;
}

这个功能首先是根据你的Key来寻找map中是否存在这个key,如果存在则直接获取到这个value返回并不会执行后面的mappingFunction方法操作,

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;
    if (old != null && (oldValue = old.value) != null) {
        afterNodeAccess(old);
        return oldValue;
    }
}

这就是其寻找key的地方,如果没有找到会继续向下执行。

V v = mappingFunction.apply(key);

这个方法apply是Function的方法,其作用就是将key放到你写的方法中进行操作然后返回value,再将value存储:

if (v == null) {
    return null;
} else if (old != 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);
    if (binCount >= TREEIFY_THRESHOLD - 1)
        treeifyBin(tab, hash);
}
++modCount;
++size;
afterNodeInsertion(true);

这就存储了value。其中afterNodeAccess和afterNodeInsertion这个是在LinkedHashMap里面的两个方法,是将map指向头的作用。

具体例子:

修改参数后: