HashMap源码(8)compute
文章目录
这个和之前的两个方法相同。
@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;
}
本方法,如果map中没有相关的key,其可以创建一个。无论该key的value是否存在他都会执行你所传的方法执行,只是当你方法执行后的返回值如果是null的话会删掉该key。其他都正常。
相关测试代码:
当map中没有该key的情况:
public static void main(String[] args) {
Map<String, String> map = new HashMap<>();
map.put("k","k");
map.compute("j",(k,v)->genValue1(k,v));
System.out.println("map中没有相关key:"+map);
}
static String genValue1(String k,String v){
System.out.println(k+v);
return k+v;
}
结果:
jnull
map中没有相关key:{j=jnull, k=k}
当map中有该key,但是value为空的时候:
public static void main(String[] args) {
Map<String, String> map = new HashMap<>();
map.put("k","k");
map.put("j",null);
map.compute("j",(k,v)->genValue1(k,v));
System.out.println("map中有相关key,但是value为null:"+map);
}
static String genValue1(String k,String v){
System.out.println(k+v);
return k+v;
}
结果:
jnull
map中有相关key,但是value为null:{j=jnull, k=k}
当map中有该key,value不为空的时候:
public static void main(String[] args) {
Map<String, String> map = new HashMap<>();
map.put("k","k");
map.put("j","zhang");
map.compute("j",(k,v)->genValue1(k,v));
System.out.println("map中有相关key,value不为null:"+map);
}
static String genValue1(String k,String v){
System.out.println(k+v);
return k+v;
}
结果:
jzhang
map中有相关key,value不为null:{j=jzhang, k=k}
当map中有该key,value不为空,但是处理方法处理结果为null的时候:
public static void main(String[] args) {
Map<String, String> map = new HashMap<>();
map.put("k","k");
map.put("j","zhang");
map.compute("j",(k,v)->genValue1(k,v));
System.out.println("map中有相关key,value不为null,处理结果为努力:"+map);
}
static String genValue1(String k,String v){
System.out.println(k+v);
return k+v;
}
结果:
jzhang
map中有相关key,value不为null,处理结果为努力:{k=k}
只有当处理方法的返回值为null的时候将会删除key,其他情况都会添加或者修改key,value.