数组:
定长数组:
val s = Array("Hello", 1)
//用()而不是[]
println("s(0) -> " + s(0)) //输出s(0) -> Hello
变长数组:
val b = ArrayBuffer[Int]()
b += 1
b +=(2, 3)
println(b)
b ++= Array(4, 5, 6)
println(b)
b.trimEnd(1)
println(b)
b.insert(2, 22)
b.insert(2, 222, 2222, 22222)
println(b)
b.remove(2)
println(b)
b.remove(2, 3)
println(b)
println(b.toArray)
println(b.toArray.toBuffer)
遍历数组
println("----------------跨2步长---------------------")
for (i <- 0 until(10, 2))
print(i)
println("\n----------------逆转----------------------")
for (i <- (0 until(10, 2)).reverse)
print(i)
println("\n----------------遍历数组--------------------")
val a = Array(1, 2, 3, "abc")
for (i <- a)
print(i)
println("\n------------------------------------------")
数组变换:
val arr1 = Array(1, 2, 3, 4, 5, 6)
val result1 = for (i <- arr1) yield i * 10
println(result1)
val arr2 = ArrayBuffer[Int]()
arr2 +=(1, 2, 3, 4, 5, 6)
val result2 = for (i <- arr2) yield i
println(result2)
println("------------------------------------------")
val result3 = for (i <- arr2 if i % 2 == 0) yield i * 10
val result4 = arr2.filter(_ % 2 == 0).map(_ * 10)
println(result3)
println(result4)
val a = ArrayBuffer(1, 2, 3, 4, -5, 8, -1, 7, -2)
var first = true
val result5 = for (i <- a if i > 0 || first) yield {
if (i < 0)
first = false
i
}
println(result5)
常用函数
println(Array(1, 2, 10).sum)
println(Array("Mary", "had", "a", "little", "lamp").max)
val a = ArrayBuffer(324, 123.2, 123, 23, 4, 12, 7)
println(a.sorted.reverse)
val b = a.toArray
scala.util.Sorting.quickSort(b)
println(b.mkString("<", ",", ">"))
其他:
val a = ArrayBuffer[Int](1, 2, 3)
a.append(4, 5, 6)
println(a.mkString("<", ",", ">"))
println(a.count(_ > 2))
def f(x: Int) = {
if (x > 2)
true
else
false
}
println(a.count(f))
a +=(1, 2, 3) -= 1 -= 5
println(a)
多维数组:
val matrix1 = Array.ofDim[Int](3, 4)
val matrix2 = Array.ofDim[Int](3, 4, 5)
matrix1(1)(2) = 1
matrix2(1)(2)(3) = 1
println(matrix1.mkString("<", ",", ">"))
println(matrix2.mkString("<", ",", ">"))
val triangle = new Array[Array[Int]](10)
for (i <- 0 until triangle.length) {
triangle(i) = new Array[Int](i)
}
练习:
def ex1(n: Int) = {
val a = new Array[Int](n)
for (i <- 0 until a.length) {
a(i) = Random.nextInt(n)
}
}
def swapAdjoin(n: Array[Int]): Array[Int] = {
var count = -1
for (i <- n) yield {
count += 1
if (count % 2 == 0) {
if (count + 1 < n.length)
n(count + 1)
else
i
} else {
n(count - 1)
}
}
}
def ex2_3 = {
println(swapAdjoin(Array(1, 2, 3, 4, 5)).mkString("<", ",", ">"))
}
def classify(n: Array[Int]): Array[Int] = {
val a = (for (i <- n if i > 0) yield i).toBuffer
a.appendAll(for (i <- n if i <= 0) yield i)
a.toArray
}
def ex4 = {
println(classify(Array(1, 2, 3, 0, -1, 2, 3, 45, -32, -43, 2, 0)).mkString("<", ",", ">"))
}
def arrayAverage(n:Array[Double]):Double = {
n.sum/n.length
}
def ex5 = {
println(arrayAverage(Array(1,2,3,5.0,7.9)))
}
def ex7 = {
println(Array(1,2,3,4,5,1,12,2,3,4,5,2,3,4,6,8).distinct.mkString("<", ",", ">"))
}