HashMap putIfAbsent作用

版权声明:本文为博主原创文章,转载请说明出处 https://blog.csdn.net/u010002184/article/details/89321479
如果key不存在或者key已存在但是值为null,才put进去
      HashMap<String, Integer> map = new HashMap<>();
        System.out.println(map.put("a", 1));//null
        System.out.println(map.put("b", 2));//null
        System.out.println(map.put("c", 3));//null
        System.out.println(map.put("d", 2));//null
        System.out.println(map.put("b", 5));//2,put新值,返回旧值

        System.out.println(map.remove("f"));//null,返回旧值
        System.out.println(map.remove("b"));//5,返回旧值
        System.out.println(map);//{a=1, c=3, d=2}

        //如果key不存在或者key已存在但是值为null,才put进去
        System.out.println(map.putIfAbsent("b", 5));//null,key
        System.out.println(map.putIfAbsent("c", 6));//3,"c"key已经存在,不put新值,返回当前值
        System.out.println(map);//{a=1, b=5, c=3, d=2}

        System.out.println(map.put("e", null));//null
        System.out.println(map);//{a=1, b=5, c=3, d=2, e=null}
        System.out.println(map.putIfAbsent("e", 6));//null
        System.out.println(map);//{a=1, b=5, c=3, d=2, e=6}
    @Override
    public V putIfAbsent(K key, V value) {
        return putVal(hash(key), key, value, true, true);
    }

putVal方法:

            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }

以上基于jdk1.8

猜你喜欢

转载自blog.csdn.net/u010002184/article/details/89321479