存储固定大小的同类型元素
def myArray(): Unit = {
var z:Array[String] = new Array[String](3) // 长度为3的数组
z(0) = "hello"
z(1) = "scala"
z(2) = "word"
z(0) = "hi"
z.foreach(println)
}
数组里面的每个元素是相同的数据类型,一般用for循环处理
多维数组一个数组中的值可以是另一个数组,另一个数组的值也可以是一个数组。矩阵与表格是我们常见的二维数组。
val myMatrix = Array.ofDim[Int](3,3)
def myArray(): Unit = {
val myMatrix = Array.ofDim[Int](3,3)
var num = 0
for(i<- 0 to 2){
for(j <- 0 to 2){
myMatrix(i)(j) = num
num += 1
}
}
for (i <- 0 to 2){
for ( j<- 0 to 2){
print(myMatrix(i)(j)+ " ")
}
println()
}
}
0 1 2
3 4 5
6 7 8
concat
++
def myArray(): Unit = {
var myList1 = Array(1.9, 2.9, 3.4, 3.5)
var myList2 = Array(8.9, 7.9, 0.4, 1.5)
var myList3 = Array.concat(myList1, myList2)
var myList4 = myList1 ++ myList2
println(myList3.mkString(","))
println(myList4.mkString(","))
}
range() 方法最后一个参数为步长,默认为 1
def myArray(): Unit = {
var myList1 = Array.range(10,20,2)
var myList2 = Array.range(10,20)
println(myList1.mkString(","))
println(myList2.mkString(","))
}