![]() |
VOOZH | about |
A list is a collection which contains immutable data. List represents linked list in Scala. A List is immutable, if we need to create a list that is constantly changing, the preferred approach is to use a ListBuffer. The Scala List class holds a sequenced, linear list of items. A List can be built up efficiently only from back to front. the ListBuffer object is convenient when we want to build a list from front to back. It supports efficient prepend and append operations. Once we are done creating our list, call the toList method. To convert the ListBuffer into a List, Time taken will be constant. To use ListBuffer, scala.collection.mutable.ListBuffer class is imported, an instance of ListBuffer is created.
Example :
var name = new ListBuffer[datatype]() // empty buffer is created
var name = new ListBuffer("class", "gfg", "geeksforgeeks")
In the above example, first, an empty buffer is created here datatype indicates the type of data such as integer, string. Then created a buffer with three elements, of type string. Below operation can be performed on ListBuffer -
Creating instance of ListBuffer:
Output:
ListBuffer(GeeksForGeeks, gfg, Class)
Access element from ListBuffer: Element is accessed same as list, ListBuffer(i) is used to accessed ith index element of list.
Output:
gfg
Adding elements in ListBuffer:
- Add single element to the buffer
ListBuffer+=( element)
- Add two or more elements (method has a varargs parameter)
ListBuffer+= (element1, element2, ..., elementN )
- Append one or more elements (uses a varargs parameter)
ListBuffer.append( elem1, elem2, ... elemN)
Output:
ListBuffer(GeeksForGeeks, gfg, class, Scala, Article)
Deleting ListBuffer Elements:
- Remove one element
ListBuffer-= (element)
- Remove multiple elements
ListBuffer-= (elem1, elem2, ....., elemN)
Output:
ListBuffer(Scala, Article)
Deleting ListBuffer Elements using ListBuffer.remove() : The remove() method is used to delete one element by its position in the ListBuffer, or a series of elements beginning at a starting position.
Output:
ListBuffer(gfg, class, Scala, Article) ListBuffer(gfg)
In Scala, a ListBuffer is a mutable sequence that represents a resizable array buffer. It allows elements to be added, removed, or updated at any position in constant time, making it useful for scenarios where frequent modifications to a list are required.
A ListBuffer is created by invoking its constructor, which takes no arguments:
List buffer: ListBuffer(1, 20, 10, 4, 5, 6) List: List(1, 20, 10, 4, 5, 6)
In this example, we create a new ListBuffer and add, remove, and update elements in it. We then convert the ListBuffer to an immutable List and print both the ListBuffer and the List. As we can see from the output, the ListBuffer contains all the elements that were added to it, and the immutable List is a copy of the ListBuffer with the same elements in the same order.
Here are some advantages and disadvantages of using ListBuffer in Scala: