问题描述
谁能解释一下可变映射中的默认值是如何工作的?
Can anyone explain how a default value in mutable map works?
scala> val mmap = mutable.Map[String, mutable.Set[String]]().withDefaultValue{mutable.Set[String]()}
mmap: scala.collection.mutable.Map[String,scala.collection.mutable.Set[String]] = Map()
scala> mmap("a") += "b"
res1: scala.collection.mutable.Set[String] = Set(b)
地图为空,没有键.
scala> mmap
res2: scala.collection.mutable.Map[String,scala.collection.mutable.Set[String]] = Map()
但我刚刚尝试编辑的关键是显示数据.
But the key I just tried to edit is showing data.
scala> mmap("a")
res3: scala.collection.mutable.Set[String] = Set(b)
为什么 res2
是空映射但 mmap("a")
有值?
Why is res2
an empty map but mmap("a")
have a value?
推荐答案
通过修改地图中不存在的键,您基本上改变了默认值,而不是添加新键.
By modifying key that does not exist in the map you basically changing the default value, not adding a new key.
假设您想添加一些东西以在地图中使用 a
键进行设置.
Let's say you want to add some stuff to set with key a
in your map.
val mmap =
mutable.Map[ String, mutable.Set[ String ] ]()
.withDefaultValue( mutable.Set[ String ]() )
// Changind default value
mmap( "a" ) += "b"
mmap( "a" ) += "c"
现在 mmap
的默认值有 2 个元素但仍然没有键.现在您更改"了另一个不存在的密钥:
Now the default value of mmap
has 2 elements but still no keys. Now you 'change' the other nonexisting key:
// Still changind default value
mmap( "c" ) += "c1"
实际上您仍在更改默认值
In reality you are still changing the default value
// Printing default value
println( mmap("a") )
// Result => Set(c, c1, b)
为了创建一个真正的键使用分配
In order to create a real key use assignment
// Creating a new key
mmap("b") = mutable.Set[ String ]( "b1", "b2" )
mmap.foreach( println )
// Result => (b,Set(b1, b2))
这篇关于mutable.Map 中 withDefaultValue 的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!