scala-数组

定长数组Array:
定义数组例子:
val nums = new Array[Int](10)
val a = new Array[String](10)
val s = Array("hello","world")
s(0) = "Goodbye" //使用()而不是[]来访问元素


变长数据:数组缓冲
import scala.collection.mutable.ArrayBuffer
val b = ArrayBuffer[Int]()
b += 10 //在尾端添加元素
b += (1,2,3,4) //在尾端添加多个元素
b ++= Array(1,2,3,4) //在尾端添追加任何集合
b.trimEnd(2)//移除最后2个元素
b.insert(2,7,8,9)//在下标之前插入任意多元素
b.remove(2,3)//从下标开始移除任意多个元素


数组与数组缓冲之间的互换:
b.toArray  a.toBuffer


遍历数组和数组缓冲
for(i <= 0 until a.length)
print a(i)

for(elem <= a)
print(elem)

数组转换
val result=for(elem <= a if elem %2 ==0) yield 2*elem
val result = a.filter(_ % 2 == 0).map(2 * _)
val result = a.filter{_ % 2 == 0}.map{2 * _}


常用算法
Array(1,2,4,7).sum

val a = Array(1,3,5,7)

val bDescending = a.sortWith(_ > _)

scala.util.Sorting.quickSort(a)
a.mkString(" and ")//1 and 3 and 5 and 7
a.mkString("<",",",">") //<1,3,5,7>


多维数组通过数组的数组来实现的,比如创建一个二维数组:
val matrix = Array.ofDim[Double](3,4)//三行 四列
matrix(row)(column) = 2


val triangle = new Array[Array[Int]](10)
triangle(0) = new Array[Int](7)

你可能感兴趣的:(scala)