Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
listbuffers的Scala哈希映射_List_Scala_Hashmap_Defaultdict - Fatal编程技术网

listbuffers的Scala哈希映射

listbuffers的Scala哈希映射,list,scala,hashmap,defaultdict,List,Scala,Hashmap,Defaultdict,我试图在Scala中模拟defaultdict(list)(我已经声明了Scala.collection.mutable.HashMap) 现在我正在努力 val d = new HashMap[Int,ListBuffer[Int]](){ override def default(key:Int) = ListBuffer[Int]() } 然后,为了添加到列表中,我尝试了以下方法: d(integerKey) += integerValToInsertIntoList 但似乎什么都不起

我试图在Scala中模拟defaultdict(list)(我已经声明了Scala.collection.mutable.HashMap)

现在我正在努力

val d = new HashMap[Int,ListBuffer[Int]](){ override def default(key:Int) = ListBuffer[Int]() }
然后,为了添加到列表中,我尝试了以下方法:

d(integerKey) += integerValToInsertIntoList

但似乎什么都不起作用,
d
表现得好像总是空的?

以下是实现可变映射的正确方法:

val d = new HashMap[Int,ListBuffer[Int]]() {
   override def apply(key: Int) = super.getOrElseUpdate(key, ListBuffer())
}
d(4) append 4
d(5) append 5
scala> d(4)
res1: scala.collection.mutable.ListBuffer[Int] = ListBuffer(4)
scala> d(5)
res2: scala.collection.mutable.ListBuffer[Int] = ListBuffer(5)

注 对于可变映射,使用带有默认值的
无法按预期工作。它将对所有新条目重复使用相同的“默认”ListBuffer()

val d = new HashMap[Int,ListBuffer[Int]]().withDefaultValue(ListBuffer())
d(4) append 4
d(5) append 5
在REPL中,我们看到d(4)(与d(5)相同)将包含两个新添加的条目:

scala> d(4)
res1: scala.collection.mutable.ListBuffer[Int] = ListBuffer(4, 5)
scala> d(5)
res2: scala.collection.mutable.ListBuffer[Int] = ListBuffer(4, 5)

我明白了我想,我做了
val d=new HashMap[Int,ListBuffer[Int]]()
,然后在做附录时,我做了
d.getOrElseUpdate(integerKey,new ListBuffer())+=integerValToInsertIntoList
,但我不知道这是正确的方法还是有更好的答案我怀疑
d(integerKey)+=integerValToInsertIntoList
integerKey
添加到
d
,因此每次它都返回一个新的空
ListBuffer
。我假设d(integerKey)指hashmap中的ListBuffer,因此+=将该项附加到缓冲区中,但我猜我错了,这似乎是一个好的解决方案。我会把这个问题留着,以防其他人有更好的答案/想要代表点。这怎么行
d(4)
将始终是相同的
ListBuffer
。如果您选中,在
d(5)append 44
之后,它将返回
d(4)
d(5)
(甚至
d(0)
4,5,44
。检查好捕获谢谢!我在不可变映射中使用了很多次,我真的认为它在可变映射中也会像预期的那样工作。。。这个可变实现似乎对所有新条目重用相同的默认值。