- Scala Collections - Discussion
- Scala Collections - Useful Resources
- Scala Collections - Quick Guide
- Scala Collections - zip
- Scala Collections - scan
- Scala Collections - reduce
- Scala Collections - partition
- Scala Collections - map
- Scala Collections - foldRight
- Scala Collections - foldLeft
- Scala Collections - fold
- Scala Collections - flatten
- Scala Collections - flatMap
- Scala Collections - find
- Scala Collections - filter
- Scala Collections - dropWhile
- Scala Collections - drop
- Scala Collections - Stream
- Scala Collections - Stack
- Scala Collections - Seq
- Scala Collections - Tuple
- Scala Collections - Queue
- Scala Collections - Option
- Scala Collections - Iterator
- Scala Collections - ListMap
- Scala Collections - HashMap
- Scala Collections - Map
- Scala Collections - TreeSet
- Scala Collections - HashSet
- Scala Collections - BitSet
- Scala Collections - Set
- Scala Collections - Vector
- Scala Collections - ListSet
- Scala Collections - ListBuffer
- Scala Collections - List
- Scala Collections - ArrayBuffer
- Scala Collections - Array using Range
- Scala Collections - Multi-Dimensional Array
- Scala Collections - Array
- Scala Collections - Environment Setup
- Scala Collections - Overview
- Scala Collections - Home
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
Scala Collections - ArrayBuffer
Scala provides a data structure, the ArrayBuffer, which can change size when initial size falls short. As array is of fix size and more elements cannot be occupied in an array, ArrayBuffer is an alternative to array where size is flexible.
Internally ArrayBuffer maintains an array of current size to store elements. When a new element is added, size is checked. In case underlying array is full then a new larger array is created and all elements are copied to larger array.
Declaring ArrayBuffer Variables
The following is the syntax for declaring an ArrayBuffer variable.
Syntax
var z = ArrayBuffer[String]()
Here, z is declared as an array-buffer of Strings which is initially empty. Values can be added by using commands pke the following −
Command
z += "Zara"; z += "Nuha"; z += "Ayan";
Processing ArrayBuffer
Below is an example program of showing how to create, initiapze and process ArrayBuffer −
Example
import scala.collection.mutable.ArrayBuffer object Demo { def main(args: Array[String]) = { var myList = ArrayBuffer("Zara","Nuha","Ayan") println(myList); // Add an element myList += "Welcome"; // Add two element myList += ("To", "Tutorialspoint"); println(myList); // Remove an element myList -= "Welcome"; // print second element println(myList(1)); } }
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
Command
>scalac Demo.scala >scala Demo
Output
ArrayBuffer(Zara, Nuha, Ayan) ArrayBuffer(Zara, Nuha, Ayan, Welcome, To, Tutorialspoint) NuhaAdvertisements