← Back to Scala Course | Chapter 6: Collections Basics | Lesson 4 of 8

ArrayBuffer

An ArrayBuffer is a stretchy row of boxes that grows or shrinks as you add or remove things. It is like a backpack that expands to hold more.

In this page:

  1. ArrayBuffer
Syntax
scala
import scala.collection.mutable.ArrayBuffer
val buffer = ArrayBuffer(value1, value2)
buffer += value
buffer -= value

ArrayBuffer

ArrayBuffer (from scala.collection.mutable) is a resizable, mutable sequence, similar to a dynamic array or ArrayList in other languages.

Unlike Array, it can grow or shrink with += and -= in addition to allowing element mutation. It's the go-to mutable collection when you need to build up a sequence incrementally.

Note: Use ArrayBuffer instead of Array when the collection's size needs to change after creation, not just its element values.

Example: ArrayBuffer

markup
import scala.collection.mutable.ArrayBuffer

object Main extends App {
  val buffer = ArrayBuffer(1, 2, 3)
  buffer += 4
  buffer += 5

  println(buffer)
  println(buffer.length)
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Forgetting import scala.collection.mutable.ArrayBuffer, so the type is not found.
  2. Using + instead of += to add an element, which creates a new buffer instead of changing the current one.
  3. Adding to a buffer while looping over it, which can give unexpected results.
🔒

Chapter Quiz — Complete all 8 topics to unlock

0/8 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.