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

前端 未结 4 1115
刺人心
刺人心 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"))
    

提交回复
热议问题