Scala的数组操作

数组在任何语言里面都是很基本、很重要的一个数据结构,在Scala中也是如此。
数组的定义:
1,定长数组:

val nums = new Array[Int](10)
val a = new Array[String](10)
val s = Array("Hello", "World")

2,变长数组

val b = ArrayBuffer[Int]()//定义一个变长数组

数组遍历:

for (i <- 0 until a.length){
    println(i + ": " + a(i))
}

或者:

for(elem <- a){
    println(elem);
}

数组操作:

s(0) = "Goodbye" // 赋值

b += 1

结果:ArrayBuffer(1)

b += (1, 2, 3, 5)

结果:ArrayBuffer(1, 1, 2, 3, 5)

b ++= Array(8, 13, 21)

结果:ArrayBuffer(1, 1, 2, 3, 5, 8, 13, 21)

b.trimEnd(5)

结果:ArrayBuffer(1, 1, 2),把最后5个元素去掉

b.insert(2, 6)

结果:ArrayBuffer(1, 1, 6, 2),在index=2处,插入6

b.insert(2, 7, 8, 9)

结果:ArrayBuffer(1, 1, 7, 8, 9, 6, 2),在index=2处,插入7,8,9三个元素

b.remove(2)

结果:ArrayBuffer(1, 1, 8, 9, 6, 2),删除index=2处的元素

b.remove(2, 3)

结果:ArrayBuffer(1, 1, 2),从index=2处,删除3个元素

b1 = b.toArray

结果:b1:Array(1, 1, 2),ArrayBuffer转化为Array

val c = Array(2, 3, 5, 7, 11)
val result = for (elem <- c) yield 2 * elem

结果:result : Array[Int] = Array(4, 6, 10, 14, 22),yield将结果赋值给result

for (elem <- c if elem % 2 == 0) yield 2 * elem

结果:Array[Int] = Array(4)
c.filter(_ % 2 == 0).map(2 * _)//更优雅的写法

其它操作:

Array(1, 7, 2, 9).sum

结果:Int = 19

ArrayBuffer("Mary", "had", "a", "little", "lamb").max

结果:String = little

val d = ArrayBuffer(1, 7, 2, 9)
val bSorted = d.sorted //排序后重新生成一个ArrayBuffer

结果:ArrayBuffer(1, 2, 7, 9)

val e = Array(1, 7, 2, 9)
scala.util.Sorting.quickSort(e)//排序作用于e本身

结果:Array(1, 2, 7, 9)

e.mkString(" and ")

结果:String = 1 and 2 and 7 and 9 生成一个字符串,由and连接起来

e.mkString("<", ",", ">")

结果:String = <1,2,7,9> 指定起止字符串,以及连接符

二维数组

val matrix = Array.ofDim[Double](3, 4)//定义矩阵
matrix(2)(1) = 42

结果:Array[Array[Double]] = Array(Array(0.0, 0.0, 0.0, 0.0), Array(0.0, 0.0, 0.0, 0.0), Array(0.0, 42.0, 0.0, 0.0))

val triangle = new Array[Array[Int]](10)
for (i <- 0 until triangle.length)
 triangle(i) = new Array[Int](i + 1)

你可能感兴趣的:(Scala的数组操作)