数组
固定长度数组
val nums = new Array[Int](10)
nums: Array[Int] = Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
scala> val s = Array("hello", "world")
s: Array[String] = Array(hello, world)
s(0) = "goodbye"
scala 修改数组时候并不使用[]
而是使用了()
数组操作实例:
import scala.collection.mutable.ArrayBuffer
scala> import scala.collection.mutable.ArrayBuffer
import scala.collection.mutable.ArrayBuffer
scala> val b = ArrayBuffer[Int]()
b: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer()
scala> b += 1
res4: b.type = ArrayBuffer(1)
scala> b += (1, 2, 3, 4, 5)
res5: b.type = ArrayBuffer(1, 1, 2, 3, 4, 5)
scala> b ++= Array(6, 7)
res6: b.type = ArrayBuffer(1, 1, 2, 3, 4, 5, 6, 7)
scala> b.trimEnd(5)
scala> b.insert(0, 0)
scala> b.insert(1,1,2,2,3,3)
scala> b.remove(2,4)
scala> b.toArray
res11: Array[Int] = Array(0, 1, 1, 1, 2)
scala 循环输出数组
for (i <- 0 until b.length)
println(i + ":" + b(i))
until 在 b.length - 1 处就会停止
设置步长:
for (i <- 0 until (b.length, 2))
增强型for循环
for (elem <- b)
返回一个新数组并且每一个元素乘3
for (elem <- b) yield 3 * elem
打印出数组长度
println(b.length)
常用方法:
scala> b.sum
res20: Int = 5
scala> b.max
res21: Int = 2
scala> b.min
res22: Int = 0
排序
b.sortWith(_ < _)
多维数组
val matrix = Array.ofDim[Double](3, 4)