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:
Syntax
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
import scala.collection.mutable.ArrayBuffer
object Main extends App {
val buffer = ArrayBuffer(1, 2, 3)
buffer += 4
buffer += 5
println(buffer)
println(buffer.length)
}
Login to try C/C++/Java/PHP code in the editor
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
- Forgetting
import scala.collection.mutable.ArrayBuffer, so the type is not found. - Using
+instead of+=to add an element, which creates a new buffer instead of changing the current one. - 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: