English 中文(简体)
Scala Collections - ListBuffer
  • 时间:2025-01-01

Scala Collections - ListBuffer


Previous Page Next Page  

Scala provides a data structure, the ListBuffer, which is more efficient than List while adding/removing elements in a pst. It provides methods to prepend, append elements to a pst.

Declaring ListBuffer Variables

The following is the syntax for declaring an ListBuffer variable.

Syntax

var z = ListBuffer[String]()

Here, z is declared as an pst-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 ListBuffer

Below is an example program of showing how to create, initiapze and process ListBuffer −

Example

import scala.collection.mutable.ListBuffer 
object Demo {
   def main(args: Array[String]) = {
      var myList = ListBuffer("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

ListBuffer(Zara, Nuha, Ayan)
ListBuffer(Zara, Nuha, Ayan, Welcome, To, Tutorialspoint)
Nuha
Advertisements