1. 程式人生 > >Scala 可變陣列 ArrayBuffer

Scala 可變陣列 ArrayBuffer

scala>

scala> import scala.collection.mutable.ArrayBuffer
import scala.collection.mutable.ArrayBuffer

scala> val numbers = new ArrayBuffer[Int]()
numbers: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer()

scala> numbers += 1
res2: numbers.type = ArrayBuffer(1)

scala> numbers += 2
res3: numbers.type = ArrayBuffer(1, 2)

scala> numbers += (3,4)
res4: numbers.type = ArrayBuffer(1, 2, 3, 4)

scala> numbers += Array(5,6,7)
<console>:14: error: type mismatch;
 found   : Array[Int]
 required: Int
       numbers += Array(5,6,7)
                       ^

scala> numbers ++= Array(5,6,7)
res6: numbers.type = ArrayBuffer(1, 2, 3, 4, 5, 6, 7)

scala> numbers.insert(0,0)

scala> numbers
res8: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(0, 1, 2, 3, 4, 5, 6, 7)

scala> numbers.remove(0,0)

scala> numbers
res10: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(0, 1, 2, 3, 4, 5, 6, 7)

scala> numbers.remove(0)
res11: Int = 0

scala> numbers
res12: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(1, 2, 3, 4, 5, 6, 7)

scala> numbers.insert(0,0)

scala> numbers
res14: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(0, 1, 2, 3, 4, 5, 6, 7)

scala> numbers.remove(0,1)

scala> numbers
res16: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(1, 2, 3, 4, 5, 6, 7)

scala> numbers.trimEnd(3)

scala> numbers
res18: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(1, 2, 3, 4)

筆記:

將一個數組中所有元素新增到某個ArrayBuffer時,用 ++=

remove(0,1)  表示將0移除1次

remove(0,0)  表示將0移除0次

trimEnd(3)  表示從尾部切掉3個元素