...

/

ArrayBuffers

ArrayBuffers

In the following lesson, you will learn about ArrayBuffers and how they differ from ordinary arrays.

Introduction

An ArrayBuffer in Scala is a collection that comes under the sequence class. Like Arrays, it is a mutable collection, hence, when elements in an ArrayBuffer are modified, the original ArrayBuffer is updated.

ArrayBuffers are very similar to arrays with the difference that you can add and remove elements from an ArrayBuffer while adding and removing elements is not possible in simple Arrays.

Array methods and operations are also available for ArrayBuffers.

Creating an ArrayBuffer

To be able to use an ArrayBuffer, we first need to import it using the package scala.collection.mutable.ArrayBuffer. Afterward, you can create and populate an ArrayBuffer the same way you create an Array.

Scala
import scala.collection.mutable.ArrayBuffer
val myFirstArrayBuffer = ArrayBuffer(1,2,3,4,5)
// Driver Code
myFirstArrayBuffer.foreach(println)

To initialize an ArrayBuffer without populating it, we need to specify the type of element it can store. Mentioning the length is not required as the ArrayBuffer will adjust the allocated space automatically when you insert or delete elements.

val newArrayBuff = new ArrayBuffer[Int]()

Adding Elements

Let’s now populate newArrayBuffer ...