Mutable HashMap with a mutable default value doesn't keep the changes [duplicate]

我怕爱的太早我们不能终老 提交于 2019-12-08 13:07:21

问题


Suppose that I want a mutable HashMap[Int, HashSet[Int]] that has

  • integers as keys
  • mutable hash sets of integers as values

I want that an empty mutable HashSet is created by default whenever a value for a new key is accessed or updated.

Here is what I tried:

import collection.mutable.{HashMap, HashSet}

val hm = HashMap
  .empty[Int, HashSet[Int]]
  .withDefault(_ => HashSet.empty[Int])

hm(42) += 1234

println(hm)

The unexpected result is an empty HashMap. I expected a hash map with (42 -> HashSet(1234)) key-value pair.

Why doesn't the HashMap save the default mutable HashSets, and how do I fix this?


回答1:


The statement

hm(42) += 1234

will create the default value (an empty HashSet), then update it by adding 1234 to it, then throw it away.


If you want to update the HashMap itself, then remove the withDefault part from the definition, and use getOrElseUpdate instead:

hm.getOrElseUpdate(42, HashSet.empty[Int]) += 1234

Alternatively, you can leave the withDefault as-is, but update your hash map as follows:

hm(42) = (hm(42) += 1234)


来源:https://stackoverflow.com/questions/52099989/mutable-hashmap-with-a-mutable-default-value-doesnt-keep-the-changes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!