1 package chapter07 2 3 import scala.collection.mutable 4 import scala.collection.mutable.ArrayBuffer 5 6 object Test02_ArrayBuffer { 7 def main(args: Array[String]): Unit = { 8 // 1. 创建可变数组 9 val arr1: ArrayBuffer[Int] = new ArrayBuffer[Int]() 10 val arr2 = ArrayBuffer(23, 57, 92) 11 12 println(arr1) 13 println(arr2) 14 15 // 2. 访问元素 16 // println(arr1(0)) // error 17 println(arr2(1)) 18 arr2(1) = 39 19 println(arr2(1)) 20 21 println("======================") 22 // 3. 添加元素 23 val newArr1 = arr1 :+ 15 //new一个新的数组进行赋值 不指向同一块地址 24 println(arr1) 25 println(newArr1) 26 println(arr1 == newArr1) 27 //可变数组ArrayBuffer 向前追加+=: 向后追加+= 28 val newArr2 = arr1 += 19 //引用 对于可变数组 不推荐把操作后的数值的引用赋值给新的数组 29 println(arr1) 30 println(newArr2) 31 println(arr1 == newArr2) 32 newArr2 += 13 33 println(arr1) 34 35 77 +=: arr1 36 println(arr1) 37 println(newArr2) 38 //append 39 arr1.append(36) 40 arr1.prepend(11, 76) 41 arr1.insert(1, 13, 59) //(位置,*多个数值) 42 println(arr1) 43 44 arr1.insertAll(2, newArr1) 45 arr1.prependAll(newArr2) 46 47 println(arr1) 48 49 // 4. 删除元素 remove 50 arr1.remove(3) 51 println(arr1) 52 53 arr1.remove(0, 10) 54 println(arr1) 55 56 arr1 -= 13 57 println(arr1) 58 59 // 5. 可变数组转换为不可变数组 60 val arr: ArrayBuffer[Int] = ArrayBuffer(23, 56, 98) 61 val newArr: Array[Int] = arr.toArray 62 println(newArr.mkString(", ")) 63 println(arr) 64 65 // 6. 不可变数组转换为可变数组 66 val buffer: mutable.Buffer[Int] = newArr.toBuffer 67 println(buffer) 68 println(newArr) 69 } 70 }