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
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")));