向 scala.collection.mutable.Map 添加元素的语法是什么?
以下是一些失败的尝试:
val map = scala.collection.mutable.Map
map("mykey") = "myval"
map += "mykey" -> "myval"
map.put("mykey","myval")
关键是您的代码的第一行不是您所期望的。
你应该使用:
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)
与往常一样,您应该质疑您是否真的需要可变映射。
不可变映射很容易构建:
val map = Map(
"mykey" -> "myval",
"myotherkey" -> "otherval"
)
可变映射在首次构建时没有什么不同:
val map = collection.mutable.Map(
"mykey" -> "myval",
"myotherkey" -> "otherval"
)
map += "nextkey" -> "nextval"
在这两种情况下,推理都将用于确定 Map 实例的正确类型参数。
您还可以在 a 中保存一个不可变映射,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
当你说
val map = scala.collection.mutable.Map
您不是在创建地图实例,而是为 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> val m1 = Map("k0" -> "v0")
m1: scala.collection.immutable.Map[String,String] = Map(k0 -> v0)
向上面的映射添加一个新的键/值对(并创建一个新映射,因为它们都是不可变的):
scala> val m2 = m1 + ("k1" -> "v1")
m2: scala.collection.immutable.Map[String,String] = Map(k0 -> v0, k1 -> v1)
var test = scala.collection.mutable.Map.empty[String, String]
test("myKey") = "myValue"
创建一个没有初始值的可变映射:
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)
var map:Map[String, String] = Map()
var map1 = map + ("red" -> "#FF0000")
打印(地图1)