import collection.mutable.Buffer object CollectionDemo6 { def main(args: Array[String]): Unit = { //可变集合类型推导 val nums = Buffer(1) for (i <- 2 to 10) nums += i println(nums) //可变集合类型定义 val nums2 = Buffer[Int]() for (i <- 1 to 10) nums2 += i println(nums2) //可变转不可变集合 println(nums2.toList) //不可变转可变 val m = Map("a" -> 1, "b" -> 2) println(m.toBuffer) //newBuilder 构建可变集合,result转为不可变集合,但是构造器知道可变集合的类型。 val ls = List.newBuilder[String] ls ++= List("a", "b", "c") println(ls.result()) } }
运行结果:
ArrayBuffer(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
ArrayBuffer(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
ArrayBuffer((a,1), (b,2))
List(a, b, c)