1、初始化定長(zhǎng)數(shù)組
//通過顯示指定類型實(shí)例化一個(gè)數(shù)組
val array01 = new Array[Int](3)
array01(0)=6
array01(1)=7
array01(2)=8
//通過隱式推斷來(lái)實(shí)例化一個(gè)數(shù)組
val array02 = Array(1,2,3)
2、初始化變長(zhǎng)數(shù)組
對(duì)于長(zhǎng)度動(dòng)態(tài)變化的數(shù)組,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) //在尾端添加多個(gè)元素
arrayBuffer ++=Array(17,18,19) //++=追加任何集合
3、遍歷數(shù)組(定長(zhǎng)數(shù)組和緩沖數(shù)組抖音文案一樣的方法)
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類的方法,返回所有小于但不包括上限的數(shù)字
4、顯示數(shù)組內(nèi)容
顯示數(shù)組或數(shù)組緩沖的內(nèi)容,可以用mkString方法,它允許你指定元素之間的分隔符。
//顯示數(shù)組內(nèi)容
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、操作緩沖數(shù)組
arrayBuffer.remove(0)
arrayBuffer.insert(0,999)
println(arrayBuffer.mkString(","))
val array03=arrayBuffer.toArray //緩沖數(shù)組轉(zhuǎn)化為定長(zhǎng)數(shù)組
println(array03.mkString(" "))
val arrayBuffer01=array01.toBuffer //定長(zhǎng)數(shù)組轉(zhuǎn)化為緩沖數(shù)組
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、數(shù)組轉(zhuǎn)化(for推導(dǎo)式和守衛(wèi)式)
推導(dǎo)式
for(i <- arrayBuffer if i % 2==0){
print(i+" ")
}
println()
//等價(jià)于
val arr=arrayBuffer.filter(_%2==0)
for(ele <- arr){
print(ele+" ")
}
12 4 6 18
12 4 6 18
守衛(wèi)式
val arr01=for(i <- array01) yield i*2
for(ele <- arr01){
print(ele+" ")
}
println()
//等價(jià)于
val arr02=array01.map(_*2)
for(ele <- arr02){
print(ele+" ")
}
12 14 16
12 14 16
|