Scala – Array Buffer

  • date 8th October, 2020 |
  • by Prwatech |
  • 0 Comments

Array in Scala is homogeneous and alterable, i.e it contains components of a similar data type and its components can change however the size of array can’t change. To make an mutable, indexed sequence whose size can change ArrayBuffer class is utilized. To utilize, ArrayBuffer, scala.collection.mutable.ArrayBuffer class is imported, a instance of ArrayBuffer is created.

An ArrayBuffer is an Array of components, as well as the store’s present size of the array. At the point when a element is added to an ArrayBuffer, this size is checked. if suppose the underlying array isn’t full, the element is straightforwardly added to the array. and if the underlying array is full then a another large array is created and all the elements are copied into it.

Example:

var name = new ArrayBuffer[datatype]()  // empty buffer is created

var name = new ArrayBuffer("Mark", "prwa", "prwatech")

Use case 1:

Creating instance of ArrayBuffer:

import scala.collection.mutable.ArrayBuffer
object prwatech {
  def main(args: Array[String])
{
    // Instance of ArrayBuffer is created
    var name = ArrayBuffer[String]() 
    name += "Prwatech"
    name += "Data Science"
    name += "Big Data"
    println(name)
}
}


Output 
ArrayBuffer(Prwatech, Data Science, Big Data)

Use case 2:

Access element from ArrayBuffer

// Scala program to access element of ArrayBuffer

import scala.collection.mutable.ArrayBuffer
// Creating Object
object GFG
{
// Main Method
def main(args: Array[String])
{
// Instance of ArrayBuffer is created
var name = ArrayBuffer[String]()
name += "Prwatech"
name += "Data Science"
name += "Big Data"

// accessing 1th index element of arraybuffer
println(name(1)) 
}
}

Output:
Data Science

Use case 3:

Deleting ArrayBuffer Elements:

import scala.collection.mutable.ArrayBuffer
// Creating Object
object Prwatech 
// Main Method
def main(args: Array[String])
{
    // Instance of ArrayBuffer is created
    var name = ArrayBuffer( "Prwatech","Data Science","Big 
data","Machine Learning","Linux","MySql" ) 
   // deletes one element
   name -= "Prwatech"     
    
   // deletes two or more elements 
   name -= ("Linux", "Machine Learning")

   // printing resultant arraybuffer
   println(name) 
 }
}

Output:
ArrayBuffer(Data Science, Big data, MySql)

 

0
0

Quick Support

image image