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

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

提交回复
热议问题