将元素添加到scala.collection.mutable.Map的语法是什么?
这是一些失败的尝试:
val map = scala.collection.mutable.Map
map("mykey") = "myval"
map += "mykey" -> "myval"
map.put("mykey","myval")
Answers:
关键是代码的第一行不是您期望的。
您应该使用:
val map = scala.collection.mutable.Map[A,B]()
然后,您可以使用多个等效的替代方法来添加项目:
scala> val map = scala.collection.mutable.Map[String,String]()
map: scala.collection.mutable.Map[String,String] = Map()
scala> map("k1") = "v1"
scala> map
res1: scala.collection.mutable.Map[String,String] = Map((k1,v1))
scala> map += "k2" -> "v2"
res2: map.type = Map((k1,v1), (k2,v2))
scala> map.put("k3", "v3")
res3: Option[String] = None
scala> map
res4: scala.collection.mutable.Map[String,String] = Map((k3,v3), (k1,v1), (k2,v2))
然后开始Scala 2.13
:
scala> map.addOne("k4" -> "v4")
res5: map.type = HashMap(k1 -> v1, k2 -> v2, k3 -> v3, k4 -> v4)
new
空括号时没有必要。
与往常一样,您应该质疑您是否真的需要可变的地图。
不可变地图的构建很简单:
val map = Map(
"mykey" -> "myval",
"myotherkey" -> "otherval"
)
可变映射在首次构建时没有什么不同:
val map = collection.mutable.Map(
"mykey" -> "myval",
"myotherkey" -> "otherval"
)
map += "nextkey" -> "nextval"
在这两种情况下,将使用推论来确定Map实例的正确类型参数。
您还可以在中保存不可变的映射,var
每次执行“更新”时,变量将使用新的不可变的映射实例进行更新。
var map = Map(
"mykey" -> "myval",
"myotherkey" -> "otherval"
)
map += "nextkey" -> "nextval"
如果没有任何初始值,则可以使用Map.empty:
val map : Map[String, String] = Map.empty //immutable
val map = Map.empty[String,String] //immutable
val map = collection.mutable.Map.empty[String,String] //mutable
map ++ Seq("another1" -> "anotherVal1", "another2" -> "anotherVal2")
当你说
val map = scala.collection.mutable.Map
您不是在创建地图实例,而是为地图类型添加别名。
map: collection.mutable.Map.type = scala.collection.mutable.Map$@fae93e
尝试以下方法:
scala> val map = scala.collection.mutable.Map[String, Int]()
map: scala.collection.mutable.Map[String,Int] = Map()
scala> map("asdf") = 9
scala> map
res6: scala.collection.mutable.Map[String,Int] = Map((asdf,9))
创建一个没有初始值的可变映射:
scala> var d= collection.mutable.Map[Any, Any]()
d: scala.collection.mutable.Map[Any,Any] = Map()
创建具有初始值的可变映射:
scala> var d= collection.mutable.Map[Any, Any]("a"->3,1->234,2->"test")
d: scala.collection.mutable.Map[Any,Any] = Map(2 -> test, a -> 3, 1 -> 234)
更新现有键值:
scala> d("a")= "ABC"
添加新的键值:
scala> d(100)= "new element"
检查更新的地图:
scala> d
res123: scala.collection.mutable.Map[Any,Any] = Map(2 -> test, 100 -> new element, a -> ABC, 1 -> 234)