给出以下构造
import scala.collection.mutable.HashMap
import scala.collection.mutable.LinkedList
private var log = new HashMap[String, LinkedList[String]]
如何附加到链接列表?
如果我使用log.get("some key").get :+ some_string
或log.get("some key").get append LinkedList(some_string)
,则不会附加列表,但会返回包含该值的新列表。 HashMap是仅返回关联值的副本而不是对值的引用吗?
偏离主题:具有高声誉的人可以将scala添加为启用标题的标记吗?它应该是一种相当知名的编程语言。
答案 0 :(得分:0)
在尝试了很多之后回答自己:使用ListBuffer
代替LinkedList
。
答案 1 :(得分:0)
使用您的第二个解决方案对我有用:
>scala
Welcome to Scala version 2.10.0 (Java HotSpot(TM) 64-Bit Server VM, Java 1.7.0_06).
Type in expressions to have them evaluated.
Type :help for more information.
scala> import scala.collection.mutable.HashMap
import scala.collection.mutable.HashMap
scala> import scala.collection.mutable.LinkedList
import scala.collection.mutable.LinkedList
scala> var log = new HashMap[String, LinkedList[String]]
log: scala.collection.mutable.HashMap[String,scala.collection.mutable.LinkedList[String]] = Map()
scala> log += ("abc" -> LinkedList("apple", "banana", "coconut"))
res0: scala.collection.mutable.HashMap[String,scala.collection.mutable.LinkedList[String]] = Map(abc
-> LinkedList(apple, banana, coconut))
scala> log.get("abc").get append LinkedList("durian")
res1: scala.collection.mutable.LinkedList[String] = LinkedList(apple, banana, coconut, durian)
scala> log("abc")
res2: scala.collection.mutable.LinkedList[String] = LinkedList(apple, banana, coconut, durian)
虽然优于get
log.get("abc") foreach (_ append LinkedList("elderberry"))
如果无法找到值,则不会抛出异常。