欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Scala 可变数组 ArrayBuffer

程序员文章站 2022-06-14 19:05:26
...
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个元素