Hey there!
Welcome to ClearUrDoubt.com.
In this post, we will look at a program to demonstrate List and ListBuffer objects in Scala.
- List is an immutable collection object whereas ListBuffer is a mutable collection object.
- List provides a way to add an element only in the beginning(using “::” (cons) operator) where as ListBuffer will enable us to add an element at the beginning(using “+=:” operator) and ending(using “+=” operator.
Let’s look at the program:
1 |
package com.clearurdoubt |
Happy Learning.
Please leave a reply in case of any queries.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
import scala.collection.mutable.ListBuffer object ListBufferDemo { def main(args: Array[String]) { val list = List() // Empty List val buffer = new ListBuffer[String] // ListBuffer // Basic List operations val list1 = " World!" :: list val list2 = "Hello" :: list1 val list3 = "Hi, " :: list2 println(list3.mkString) println // ListBuffer operations buffer += "Hello" // add the element buffer += " World!" // append the element println(buffer.toList.mkString) "Hi, " +=: buffer // prepending the element println(buffer.toList.mkString) } } |
Output:
Happy Learning.
Please leave a reply in case of any queries.