1、初始化定长数组
//通过显示指定类型实例化一个数组
val array01 = new Array[Int](3)
array01(0)=6
array01(1)=7
array01(2)=8
//通过隐式推断来实例化一个数组
val array02 = Array(1,2,3)
2、初始化变长数组
对于长度动态变化的数组,java中是ArrayList, Scala中是ArrayBuffer
import scala.collection.mutable.ArrayBuffer
val arrayBuffer = new ArrayBuffer[Int]()
//val arrayBuffer = ArrayBuffer[Int]() //也可以去掉new
arrayBuffer += 11 //在尾端添加元素
arrayBuffer += 12
arrayBuffer +=(4,5,6) //在尾端添加多个元素
arrayBuffer ++=Array(17,18,19) //++=追加任何集合
3、遍历数组(定长数组和缓冲数组一样的方法)
for(i <- 0 until arrayBuffer.length ){
println(arrayBuffer(i))
}
for(i <- 0 to arrayBuffer.length-1){
println(arrayBuffer(i))
}
for(ele <- arrayBuffer){
println(ele)
}
utiI是Richlnt类的方法,返回所有小于但不包括上限的数字
4、显示数组内容
显示数组或数组缓冲的内容,可以用mkString方法,它允许你指定元素之间的分隔符。
//显示数组内容
val str01=array02.mkString("{",",","}")
println(str01)
val str02=array02.mkString(",")
println(str02)
val arrayBuffer_str01= arrayBuffer.mkString(",")
println(arrayBuffer_str01)
val arrayBuffer_str02= arrayBuffer.mkString("{",",","}")
println(arrayBuffer_str02)
{1,2,3}
1,2,3
11,12,4,5,6,17,18,19
{11,12,4,5,6,17,18,19}
5、操作缓冲数组
arrayBuffer.remove(0)
arrayBuffer.insert(0,999)
println(arrayBuffer.mkString(","))
val array03=arrayBuffer.toArray //缓冲数组转化为定长数组
println(array03.mkString(" "))
val arrayBuffer01=array01.toBuffer //定长数组转化为缓冲数组
arrayBuffer01 +=(111,222)
println(arrayBuffer01.mkString(" "))
999,12,4,5,6,17,18,19
999 12 4 5 6 17 18 19
6 7 8 111 222
6、数组转化(for推导式和守卫式)
推导式
for(i <- arrayBuffer if i % 2==0){
print(i+" ")
}
println()
//等价于
val arr=arrayBuffer.filter(_%2==0)
for(ele <- arr){
print(ele+" ")
}
12 4 6 18
12 4 6 18
守卫式
val arr01=for(i <- array01) yield i*2
for(ele <- arr01){
print(ele+" ")
}
println()
//等价于
val arr02=array01.map(_*2)
for(ele <- arr02){
print(ele+" ")
}
12 14 16
12 14 16