ArrayBuffer, Part 1

ArrayBuffer, Part 1: Creating and Reading (Accessing)

Use the Scala ArrayBuffer type when you want:

  • A mutable sequential collection type
  • An indexed sequence, meaning that you can access any element in the sequence in constant or near-constant time

ArrayBuffer is your primary “go to” sequence for object-oriented programming (OOP).

Creating an ArrayBuffer

Examples of how to create an ArrayBuffer:

import scala.collection.mutable.ArrayBuffer

// empty
val fruits = ArrayBuffer[String]()
val ints = ArrayBuffer[Int]()
val people = ArrayBuffer[Person]()

// with elements
val fruits = ArrayBuffer("apple", "banana", "cherry")
val ints = ArrayBuffer(1, 2, 3)

How to access (read) ArrayBuffer elements

Examples of how to access ArrayBuffer elements:

// access by index
fruits(0)
fruits(1)

// access in a `for` loop
for i <- ints do println(i)

// Updating elements with += and ++=:
val nums = ArrayBuffer(1, 2, 3)   # ArrayBuffer(1, 2, 3)
nums += 4                         # ArrayBuffer(1, 2, 3, 4)
nums += (5, 6)                    # ArrayBuffer(1, 2, 3, 4, 5, 6)
nums ++= List(7, 8)               # ArrayBuffer(1, 2, 3, 4, 5, 6, 7, 8)

More details

For more details and examples, see: