How does java.util.Map's getOrDefault() work?

前端 未结 4 1121
刺人心
刺人心 2021-02-07 00:47

I noticed that if I do map.getOrDefault(\"key1\", new Object()), even if object is present for key1 in the map, new Object() is created. Though it is n

4条回答
  •  庸人自扰
    2021-02-07 01:36

    look in the java 8 implementation:

    default V getOrDefault(Object key, V defaultValue) {
        V v;
        return (((v = get(key)) != null) || containsKey(key))
            ? v
            : defaultValue;
    }
    

    the doc specifies:

    Returns the value to which the specified key is mapped, or defaultValue if this map contains no mapping for the key. ault

    it will return the default is not present in the map

    example:

        Map map = new HashMap<>();
    
        map.put("1", "Foo");
        //search for the entry with key==1, since present, returns foo
        System.out.println(map.getOrDefault("1", "dumnba"));
        //search for the entry with key==2, since not present, returns dumnba
        System.out.println(map.getOrDefault("2", "dumnba"));
    

提交回复
热议问题