11.8. Creating an Array Whose Size Can Change (ArrayBuffer)
Problem
You want to create an array whose size can change, i.e., a completely mutable array.
Solution
An Array
is mutable in that its
elements can change, but its size can’t change. To create a mutable,
indexed sequence whose size can change, use the ArrayBuffer
class.
To use an ArrayBuffer
, import
it into scope and then create an instance. You can declare an ArrayBuffer
without initial elements, and then
add them later:
import
scala.collection.mutable.ArrayBuffer
var
characters
=
ArrayBuffer
[
String
]()
characters
+=
"Ben"
characters
+=
"Jerry"
characters
+=
"Dale"
You can add elements when you create the ArrayBuffer
, and continue to add elements
later:
// initialize with elements
val
characters
=
collection
.
mutable
.
ArrayBuffer
(
"Ben"
,
"Jerry"
)
// add one element
characters
+=
"Dale"
// add two or more elements (method has a varargs parameter)
characters
+=
(
"Gordon"
,
"Harry"
)
// add multiple elements with any TraversableOnce type
characters
++=
Seq
(
"Andy"
,
"Big Ed"
)
// append one or more elements (uses a varargs parameter)
characters
.
append
(
"Laura"
,
"Lucy"
)
Those are the most common ways to add elements to an ArrayBuffer
(and other mutable sequences). The
next recipe demonstrates methods to delete ArrayBuffer
elements.
Get Scala Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.