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

前端 未结 4 1117
刺人心
刺人心 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:26

    All the arguments to a function are evaluated before the function is executed. Java needs to evaluate new Empl("dumnba") so it can pass the result into getOrDefault. It can't know before getOrDefault is called that one of the arguments is not going to be required.

    If you want to provide a default that is not computed unless needed, you can use computeIfAbsent. For this, you pass in a function, and that function is only executed if the default value is required.

    map.computeIfAbsent("1", key -> new Empl("dumnba"))
    
    0 讨论(0)
  • 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<String, String> 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"));
    
    0 讨论(0)
  • 2021-02-07 01:40

    Shouldn't the default object be created only if it is not there in the map ?

    How could that be the case? This call:

    map.getOrDefault("1", new Empl("dumnba"))
    

    is equivalent to:

    String arg0 = "1";
    Empl arg1 = new Empl("dumnba");
    map.getOrDefault(arg0, arg1);
    

    In other words, all arguments are evaluated before being passed to the method.

    You could potentially use computeIfAbsent instead, but that will modify the map if the key was absent, which you may not want:

    System.out.println(map.computeIfAbsent("1", k -> new Empl("dumnba")));
    
    0 讨论(0)
  • 2021-02-07 01:42

    This is not because of how the map is implemented, it is because of how Java works. The runtime interpreter has to create the object first (the new Empl part) before it can actually invoke the method (the getOrDefault part).

    0 讨论(0)
提交回复
热议问题