具有可变默认值的可变HashMap不会保留更改 [英] Mutable HashMap with a mutable default value doesn't keep the changes

查看:84
本文介绍了具有可变默认值的可变HashMap不会保留更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我想要一个可变的HashMap[Int, HashSet[Int]]具有

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

  • 将整数作为键
  • 可变个整数作为值的哈希集
  • integers as keys
  • mutable hash sets of integers as values

我希望在每次访问或更新新键的值时默认创建一个空的可变HashSet.

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

这是我尝试过的:

import collection.mutable.{HashMap, HashSet}

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

hm(42) += 1234

println(hm)

意外的结果是空的HashMap.我期望具有(42 -> HashSet(1234))键值对的哈希映射.

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

HashMap为什么不保存默认的可变HashSet s,我该如何解决?

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

推荐答案

语句

hm(42) += 1234

将创建默认值(空的HashSet),然后通过添加1234对其进行更新,然后将其丢弃.

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

如果要更新HashMap本身,则从定义中删除withDefault部分,并改用getOrElseUpdate:

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


或者,您可以保持withDefault不变,但是按以下方式更新哈希映射:


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

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

这篇关于具有可变默认值的可变HashMap不会保留更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆