Scala中的ArrayBuffer (ArrayBuffer In Scala)
In Scala, arrays are immutable and contain homogenous elements i.e. the size of the array cannot be changed and all the elements of the array contain the same elements.
在Scala中, 数组是不可变的,并且包含同质元素,即数组的大小无法更改,并且数组的所有元素都包含相同的元素。
ArrayBuffer is a special class the is used to create a mutable array.
ArrayBuffer是一个特殊的类,用于创建可变数组。
To use the ArrayBuffer we will import,
要使用ArrayBuffer,我们将导入
scala.collection.mutable.ArrayBuffer
Syntax:
句法:
Syntax to create an ArrayBuffer in Scala,
在Scala中创建ArrayBuffer的语法,
var arrayBuffer = ArrayBuffer("element1", "element2", ...)
程序创建一个ArrayBuffer (Program to create an ArrayBuffer)
import scala.collection.mutable.ArrayBuffer
object MyClass {
def main(args: Array[String]) {
println("My bikes are ")
val bikes = ArrayBuffer("ThunderBird 350", "YRF R3")
for(i <- 0 to bikes.length-1)
println(bikes(i))
// adding a string
bikes += "iron 883"
println("After adding new bike to my collection")
for(i <- 0 to bikes.length-1)
println(bikes(i))
}
}
Output
输出量
My bikes are
ThunderBird 350
YRF R3
After adding new bike to my collection
ThunderBird 350
YRF R3
iron 883
You can add new element(s) to the ArrayBuffer using the += operator and using the append() method.
您可以使用+ =运算符并使用append()方法将新元素添加到ArrayBuffer中 。
向ArrayBuffer添加新元素 (Adding new elements to ArrayBuffer)
import scala.collection.mutable.ArrayBuffer
object MyClass {
def main(args: Array[String]) {
println("My bikes are ")
val bikes = ArrayBuffer[String]()
bikes += "ThunderBird 350"
bikes += ("YRF R3", "Iron 883")
bikes.append("BMW S1000 RR")
for(i <- 0 to bikes.length-1)
println(bikes(i))
}
}
Output
输出量
My bikes are
ThunderBird 350
YRF R3
Iron 883
BMW S1000 RR
删除数组元素 (Deleting array elements)
You can also delete elements of the ArrayBuffer using -= operator and ArrayBuffer.remove() method.
您还可以使用-=运算符和ArrayBuffer.remove()方法删除ArrayBuffer的元素。
Syntax:
句法:
Deleting one element using -= operator
使用-=运算符删除一个元素
ArrayBuffer -= (arrayElement)
Deleting multiple-elements using -= operator
使用-=运算符删除多个元素
ArrayBuffer -= (arrayElement1, arrayElement2, ...)
Deleting element using remove method
使用remove方法删除元素
ArrayBuffer -= (arrayElementposition)
删除ArrayBuffer元素的程序 (Program to delete elements of ArrayBuffer)
import scala.collection.mutable.ArrayBuffer
object MyClass {
def main(args: Array[String]) {
val bikes = ArrayBuffer("ThunderBird 350", "YRF R3", "Iron 883", "BMW S1000 RR", "BMW GSA")
println("My bikes are ")
for(i <- 0 to bikes.length-1)
println(bikes(i))
println("Removing elements...")
bikes -= "YRF R3"
bikes -= ("Iron 883", "BMW GSA")
bikes.remove(1)
for(i <- 0 to bikes.length-1)
println(bikes(i))
}
}
Output
输出量
My bikes are
ThunderBird 350
YRF R3
Iron 883
BMW S1000 RR
BMW GSA
Removing elements...
ThunderBird 350
These were some operations on ArrayBuffer which is a special class that creates an Array mutable.
这些是对ArrayBuffer的一些操作,它是一个创建Array可变变量的特殊类。
翻译自: https://www.includehelp.com/scala/arraybuffer-in-scala-creating-mutable-arrays.aspx