1. 程式人生 > >scala:陣列

scala:陣列




定義一個長度不變的整型陣列:

val a = new Array[int](10) 
//Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0)

定義有初值的陣列,不用new

val s = Array("a", "b") 
//長度為2的Array[String],通過初值確定型別

取用數組裡面的值用(),而不是用[]println(s(0))

定義可變長度陣列

import scala.collection.mutable.ArrayBuffer

scala> val b = ArrayBuffer[Int]()
b: scala.
collection.mutable.ArrayBuffer[Int] = ArrayBuffer() scala> b += 1 res107: b.type = ArrayBuffer(1) scala> b += (1,2) res108: b.type = ArrayBuffer(1, 1, 2) scala> b ++= Array(3, 8) res109: b.type = ArrayBuffer(1, 1, 2, 3, 8) scala> b.toArray res112: Array[Int] = Array(1, 1, 2, 3, 8) scala>
res112.toBuffer res113: scala.collection.mutable.Buffer[Int] = ArrayBuffer(1, 1, 2, 3, 8)

陣列運算

不會改變原陣列,適用於ArrayBuffer

Array(1,2,3).sum
Array(1,2,3).max
Array(1,2,3).min
Array(3,2,3).sorted

quickSort會重新排列原陣列,但不適用於ArrayBuffer

scala> val arr = Array(2,3,2)
arr: Array[Int] = Array(2, 3, 2
) scala> scala.util.Sorting.quickSort(arr) scala> arr res14: Array[Int] = Array(2, 2, 3)