How to create an Array whose size can change (ArrayBuffer)

This is an excerpt from the Scala Cookbook (partially modified for the internet). This is one the shortest recipes in the book, Recipe 11.8, “How to Create 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.

The Scala Cookbook

This tutorial is sponsored by the Scala Cookbook, which I wrote for O’Reilly:

You can find the Scala Cookbook at these locations:

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.