computeIfAbsent and putIfAbsent

发现了这两个有趣的map内置方法,发现还是有很多不同的

1. garbage usage:

putIfAbsent 运行情况就像是:

V v = map.get(key);
 if (v == null)
     v = map.put(key, value);

 return v;

computeIfAbsent 运行就像是:

if (map.get(key) == null) {
     V newValue = mappingFunction.apply(key);
     if (newValue != null)
         map.put(key, newValue);
 }

对于很占内存的值,比如说是 new ArrayList<>(), putIfAbsent 都会先创建一个值,然后如果map中存在这个key, 再忽略掉这个新n创建的值,会浪费很多空间,调用没有必要的垃圾回收

2. return value

computeIfAbsent: 返回当前或者是新存入的,与key相关的值,或者是NULL(只有在compute value是NULL的情况下)putIfAbsent: 返回上一个与key对应的值,或者是NULL(如果当前key没有对应的值)

如果key已经存在,二者没有太大区别,如果key不存在,computeIfAbsent 返回 compute value,putIfAbsent 返回NULL

3. input value

对于Absent的定义:key不存在,或者key所对应的值是NULL

computeIfAbsent: 不会放入NULL value 如果key不存在

putIfAbsent: 会放入NULL值

这个对于getOrDefault and containsKey有不同的影响