本篇主要涉及Scala中数组的使用。
3.1 定长数组
val nums = new Array[Int](10)
// An array of ten integers, all initialized with zero
val a = new Array[String](10)
// A string array with ten elements, all initialized with null
val s = Array("Hello", "World")
// An Array[String] of length 2—the type is inferred
// Note: No new when you supply initial values
s(0) = "Goodbye"
// Array("Goodbye", "World")
// Use () instead of [] to access elements
如果提供初始值,则不需要new
。
使用()
访问数组中的元素。
3.2 可变长数组: Array Buffers
import scala.collection.mutable.ArrayBuffer
val b = ArrayBuffer[Int]()
// Or new ArrayBuffer[Int]
// An empty array buffer, ready to hold integers
b += 1
// ArrayBuffer(1)
// Add an element at the end with +=
b += (1, 2, 3, 5)
// ArrayBuffer(1, 1, 2, 3, 5)
// Add multiple elements at the end by enclosing them in parentheses
b ++= Array(8, 13, 21)
// ArrayBuffer(1, 1, 2, 3, 5, 8, 13, 21)
// You can append any collection with the ++= operator
b.trimEnd(5)
// ArrayBuffer(1, 1, 2)
// Removes the last five elements
使用+=
将新元素加入数组尾部。
使用++=
将一个Array中的元素都加入数组。
b.insert(2, 6)
// ArrayBuffer(1, 1, 6, 2) // Insert before index 2
b.insert(2, 7, 8, 9)
// ArrayBuffer(1, 1, 7, 8, 9, 6, 2)
// You can insert as many elements as you like
b.remove(2)
// ArrayBuffer(1, 1, 8, 9, 6, 2)
b.remove(2, 3)
// ArrayBuffer(1, 1, 2)
// The second parameter tells how many elements to remove
增加或删除数组尾部的元素,效率较高。
b.toArray
可以将变长数组变为定长数组,类似的有a.toBuffer
。
3.3 数组遍历
for (i <- 0 until a.length)
println(i + ": " + a(i))
//The variable i goes from 0 to a.length - 1.
如果不需要数组下标,还可以采用:
for (elem <- a)
println(elem)
3.4 改变数组
val a = Array(2, 3, 5, 7, 11)
val result = for (elem <- a) yield 2 * elem
// result is Array(4, 6, 10, 14, 22)
不会改变原有的数组,而是生成一个新的数组。
for (elem <- a if a % 2 == 0) yield 2 * elem
a.filter(_ % 2 == 0).map(2 * _)
a filter { _ % 2 == 0 } map { 2 * _ }
这三种写法效果一样,允许在for语句里加入一个if
判断。
3.5 基本算法
Array(1, 7, 2, 9).sum // 19,Works for ArrayBuffer too
ArrayBuffer("Mary", "had", "a", "little", "lamb").max // "little"
val b = ArrayBuffer(1, 7, 2, 9)
val bSorted = b.sorted(_ < _)
// b is unchanged; bSorted is ArrayBuffer(1, 2, 7, 9)
sorted
方法对array或者array buffer排序,返回排完序的数组,不会改变原有的数组。
val a = Array(1, 7, 2, 9)
scala.util.Sorting.quickSort(a)
// a is now Array(1, 2, 7, 9)
上面这种方法,只能对定长数组使用。
a.mkString(" and ")
// "1 and 2 and 7 and 9"
a.mkString("<", ",", ">")
// "<1,2,7,9>"
使用mkString
方法,展示数组的内容。
3.6 多维数组
val matrix = Array.ofDim[Double](3, 4) // Three rows, four columns
matrix(row)(column) = 42
每个维度长度不同的数组:
val triangle = new Array[Array[Int]](10)
for (i <- 0 until triangle.length)
triangle(i) = new Array[Int](i + 1)