There are several mutable collection classes in Scala.
Array Buffers
List Buffers
StringBuilders
Queues
Stacks
Mutable ArraySeqs
Hash Tables
Weak Hash Maps
Concurrent Maps
Mutable Bitsets
Let’s cover some important mutable collection classes in this shot.
An ArrayBuffer
in Scala is used to build large collections of data. It is used to hold an array along with the size of the array. The dominant ArrayBuffer
operations include accessing the array, modifying the array, appending the array, etc.
scala> val buf = scala.collection.mutable.ArrayBuffer.empty[Int]
buf: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer()
ListBuffer
is similar to ArrayBuffer
; however, list buffers use a linked list instead of an array in its implementation. List buffers are mainly used when a programmer wishes to convert a buffer to a list.
scala> val buf = scala.collection.mutable.ListBuffer.empty[Int]
buf: scala.collection.mutable.ListBuffer[Int] = ListBuffer()
StringBuilder
is used to build strings – they are directly imported in the default namespace. You can easily create them using the syntax below.
scala> val buf = new StringBuilder
ArrayDeque
is used for appending and prepending elements in a buffer. It uses a resizable array for this purpose.
Scala provides the use of mutable queues (mQueue
). The only difference between mutable queues and immutable queues is the use of +=
and ++=
operators to perform append the queue.
Dequeuing a mutable queue just removes the first element.
scala> val queue = new scala.collection.mutable.Queue[String]
queue: scala.collection.mutable.Queue[String] = Queue()
Stacks are part of a Scala mutable collection and allow data to be retrieved in a last-in-first-out (LIFO) fashion. You need to import the class mutable.Stack
in order to use it.
scala> val stack = new scala.collection.mutable.Stack[Int]
stack: scala.collection.mutable.Stack[Int] = Stack()
Hash Tables are used to store elements in an array based on their hash values. Adding and accessing an element from the Hash table takes constant time, , unless there are collisions. One can access hash table using mutable.HashSet
and mutable.HashMap
.
Hash sets and maps can be used interchangeably, like any other set or map.
scala> val map = scala.collection.mutable.HashMap.empty[Int,String]
map: scala.collection.mutable.HashMap[Int,String] = Map()
Free Resources