理解hashmap(以Arraylist为值)put方法

Wha*_*ode 0 java arraylist hashmap

我很难理解我之前遇到的一些事情。我有DictionaryOfTranslations一个名为 的类,它有一个名为add.

此类具有的唯一实例变量是private HashMap<String, ArrayList<String>> dictionary;.

这是 add 方法的样子:

public void add(String word, String translation) {
    this.dictionary.putIfAbsent(word, new ArrayList<>());
    
    ArrayList<String> completed = this.dictionary.get(word);
    completed.add(translation);
    this.dictionary.put(word, completed);
}
Run Code Online (Sandbox Code Playgroud)

我遇到的麻烦是要理解为什么最后一行代码:this.dictionary.put(word, completed);显然是多余的。如果我注释掉这一行,结果是完全一样的。我的问题是:为什么不必专门调用put()此哈希映射上的方法,将更新后的 Arraylist 添加到其中?

And*_*ner 5

由于putIfAbsent以前的原因,它是多余的。你已经确保它存在,为了get它,所以put再次将它调回来不会改变任何东西。

当然,这段代码比它需要的更冗长,并且可能会不必要地分配一个新列表。反而:

this.dictionary.computeIfAbsent(word, k -> new ArrayList<>()).add(translation);
Run Code Online (Sandbox Code Playgroud)