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

Manoj Suthar :

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 not returned by the method but it still creates it. For example,

public class Empl {
    private int id;
    private String name;

    public Empl(String name) {
        // TODO Auto-generated constructor stub
        System.out.println(name);
        this.name = name;
    }
    @Override
    public String toString() {
        // TODO Auto-generated method stub
        return name+id;
    }
}

running following,

Map<String, Empl> map = new HashMap<String, Empl>();
Empl imp = new Empl("timon");
map.put("1", imp);
System.out.println(map.getOrDefault("1", new Empl("dumnba")));

gives this output:

timon
dumnba
timon0

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

Jon Skeet :

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

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=429004&siteId=1