0

Given is the following construct

import scala.collection.mutable.HashMap 
import scala.collection.mutable.LinkedList
private var log = new HashMap[String, LinkedList[String]]

How do I append to the linked list?

If I use log.get("some key").get :+ some_string or log.get("some key").get append LinkedList(some_string) the list is not appended but a new list containing the value is returned. Does HashMap only return a copy of the associated value instead of a reference to the value?

Off topic: Can someone with a high reputation add scala as a title-enabled tag? It should as it is a fairly known programming language.

4

2 回答 2

0

在尝试了很多之后回答自己:它使用 aListBuffer而不是LinkedList.

于 2013-05-03T22:17:11.003 回答
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"))

如果找不到该值,则不会引发异常。

于 2013-05-04T02:33:23.580 回答