集合类型 - Collection
scala的集合类型(Collection)包含如下常见的类型:
Array,List,Set,Range,Iterator,Map,Tuple
知识点:
- scala的Array分为定长数组和变长数组
- 定长:immutable
- 变长:mutable
- 通过下标操作Array,下标从0开始。通过(index),不同于java的[index]
object Demo03 {
println("Welcome to the Scala worksheet") //> Welcome to the Scala worksheet
//创建一个定长数组并赋值
val a1=Array(1,2,3,4) //> a1 : Array[Int] = Array(1, 2, 3, 4)
//创建一个定长数组,指定泛型以及长度
val a2=new Array[Int](3) //> a2 : Array[Int] = Array(0, 0, 0)
//创建变长数组并赋值。可以追加新元素的
val a3=scala.collection.mutable.ArrayBuffer(1,2,3,4)
//> a3 : scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(1, 2, 3, 4)
//通过下标取值
a1.apply(0) //> res0: Int = 1
a1(0) //> res1: Int = 1
//通过下标赋值
a1(0)=10
a1 //> res2: Array[Int] = Array(10, 2, 3, 4)
//对变长Array追加数据
a3.append(5,6)
a3 //> res3: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(1, 2, 3, 4, 5,