具有可变默认值的可变HashMap不保留更改[重复]

问题描述 投票:0回答:1

这个问题在这里已有答案:

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

  • 整数作为键
  • 可变哈希整数集合作为值

我希望只要访问或更新新密钥的值,就会默认创建一个空的可变HashSet

这是我尝试过的:

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))键值对的哈希映射。

为什么HashMap不保存默认的可变HashSets,我该如何解决这个问题呢?

scala hashmap default-value scala-collections mutable
1个回答
0
投票

该声明

hm(42) += 1234

将创建默认值(空HashSet),然后通过向其添加1234来更新它,然后将其丢弃。


如果你想更新HashMap本身,那么从定义中删除withDefault部分,并使用getOrElseUpdate代替:

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

或者,您可以按原样保留withDefault,但更新哈希映射如下:

hm(42) = (hm(42) += 1234)
© www.soinside.com 2019 - 2024. All rights reserved.