在Scala的集合中,分为不可变和可变类型。如array具有可变性,list保持不变。对于set和map来说,Scala同样有可变和不可变的。(这里的可变与不可变是针对其元素)
set类型
set分为可变和不可变类型。默认情况下,它是不变的。
scala> var testSet= Set("This","is","Friday") testSet: scala.collection.immutable.Set[String] = Set(This, is, Friday) scala> testSet += "Hello" scala> testSet res25: scala.collection.immutable.Set[String] = Set(This, is, Friday, Hello) scala> println(testSet.contains("Hello")) true当需要可变的时,可以import 可变的set
scala> import scala.collection.mutable.Set import scala.collection.mutable.Set scala> val testSet1=Set("This","is","Friday") testSet1: scala.collection.mutable.Set[String] = Set(Friday, This, is) scala> testSet1 += "Hello" res29: testSet1.type = Set(Friday, This, is, Hello) scala> testSet1 res30: scala.collection.mutable.Set[String] = Set(Friday, This, is, Hello) scala> println(testSet1.contains("Hello")) trueset类继承图
映射Map
Map也分为可变和不可变的,使用方式和Set一样。
scala> import scala.collection.mutable.Map import scala.collection.mutable.Map scala> val testMap = Map[Int, String]() testMap: scala.collection.mutable.Map[Int,String] = Map() scala> testMap +=(1 -> "This") res32: testMap.type = Map(1 -> This) scala> testMap +=(2 -> "is") res33: testMap.type = Map(2 -> is, 1 -> This) scala> testMap +=(3 -> "Friday") res34: testMap.type = Map(2 -> is, 1 -> This, 3 -> Friday) scala> println(testMap(2)) is scala> println(testMap(3)) Friday
快速初始化:
scala> val romanNumeral = Map(1 -> "I",2 -> "II",3 -> "III",4 -> "IV",5 -> "V") romanNumeral: scala.collection.mutable.Map[Int,String] = Map(2 -> II, 5 -> V, 4 -> IV, 1 -> I, 3 -> III) scala> println(romanNumeral(4)) IV