一、定长数组

scala> val a = new Array[String](5)
a: Array[String] = Array(null, null, null, null, null)

scala> a(0) = "hello" 

scala> a(0)
res2: String = hello

使用Apply特性创建数组

类名() 方式新建数组

scala> val b = Array("hadoop", "spark", "storm")
b: Array[String] = Array(hadoop, spark, storm)

scala> b(1)
res3: String = spark

// 数组是引用类型,这里修改的数组里面的值,并没有改变数组的指针,所以b是val类型,可以修改数组里面的内容
scala> b(2) = "book"

scala> b(2) 
res5: String = book

常用数组自带的函数

scala> b.length
res7: Int = 3

scala> val c = Array(1,2,3,4,5,6,7)
c: Array[Int] = Array(1, 2, 3, 4, 5, 6, 7)

scala> c.max
res8: Int = 7

scala> c.min
res9: Int = 1

scala> c.sum
res10: Int = 28

scala> c.mkString
res11: String = 1234567

scala> c.mkString("-")
res19: String = 1-2-3-4-5-6-7

scala> c.mkString("-", "!", "=")
res18: String = -1!2!3!4!5!6!7=

二、可变数组

mutable [ˈmju:təbl] adj.易变的,性情不定的;

scala> val d = scala.collection.mutable.ArrayBuffer[Int]()
d: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer()

// 定长数组是没有指定长度的
scala> d.length
res1: Int = 0

追加

scala> val c = scala.collection.mutable.ArrayBuffer[Int]()
c: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer()

scala> c += 1
res2: c.type = ArrayBuffer(1)

scala> c += 2
res3: c.type = ArrayBuffer(1, 2)

scala> println(c)
ArrayBuffer(1, 2)

scala> c += (3,4,5)        // 追加多个元素
res5: c.type = ArrayBuffer(1, 2, 3, 4, 5)

scala> c ++= Array(6,7,8)  // 两个加好,直接把一个数组追加
res6: c.type = ArrayBuffer(1, 2, 3, 4, 5, 6, 7, 8)

指定位置插入

scala> c.insert(0, 0)     // 指定在第0位置,插入0

scala> println(c)
ArrayBuffer(0, 1, 2, 3, 4, 5, 6, 7, 8)

指定位置删除

scala> c.remove(1)
res9: Int = 1

scala> println(c)
ArrayBuffer(0, 2, 3, 4, 5, 6, 7, 8)

scala> c.remove(0, 3)  // 从0位置开始,删除3个元素

scala> println(c)
ArrayBuffer(4, 5, 6, 7, 8)


scala> c.trimEnd(2)  // 末尾删除2位

scala> println(c)
ArrayBuffer(4, 5, 6)

迭代

根据下标取

for(i <- 0 until c.length){
  println(i)
}

反过来取

for(i <- (0 until c.length).reverse){
  println(i)
}

直接取(常用)

for(ele <- c){
  println(ele)
}

三、可变数组转成定长数组

scala> c.toArray
res15: Array[Int] = Array(4, 5, 6)