scala 学习(三)——Array和ArrayBuffer

scala 学习(三)——Array和ArrayBuffer

首先需要注意的是Array是定长数组,而ArrayBuffer是可变数组。下面是一个小例子,对数据进行便利和修改的操作。
//定长数组Array
val nums = new Array[Int](10)
val array1 = Array(1 to 10: _*);

val strarray = Array("aa","bb","cc","dd")

//for( i <- nums){
//    println(i)
//}
println(nums.mkString(","))
println("====================")

//for( i <- array1){
//    println(i)
//}
println(array1.mkString(","))
println("====================")

//for( i <- strarray){
//    println(i)
//}
println(strarray.mkString(","))
println("====================")

//导入ArrayBuffer的包
import scala.collection.mutable.ArrayBuffer
//变长数组ArrayBuffer
var numArrayBuffer = new ArrayBuffer[Int]();

//变长数组追加 
numArrayBuffer +=1
numArrayBuffer +=4
numArrayBuffer +=2
numArrayBuffer +=5
numArrayBuffer +=(6,7,8)
numArrayBuffer ++=array1


//for( i <- numArrayBuffer){
//    println(i)
//}
println(numArrayBuffer.mkString(","))
println("====================")


//移除最后的三个元素
numArrayBuffer.trimEnd(4);
//移除开始的两个元素
numArrayBuffer.trimStart(4);
//插入 在第2个位置插入100
numArrayBuffer.insert(2,100);
//移除 从3开始移除,移除4个
numArrayBuffer.remove(3,4);

//for( i <- numArrayBuffer){
//    println(i)
//}
println(numArrayBuffer.mkString(","))
println("====================")

下面是运行结果:

scala 学习(三)——Array和ArrayBuffer_第1张图片

你可能感兴趣的:(scala,scala)