Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

scala
mutable

What are concrete mutable collection classes in Scala?

Sarvech Qadir

There are several mutable collection classes in Scala.

  1. Array Buffers

  2. List Buffers

  3. StringBuilders

  4. Queues

  5. Stacks

  6. Mutable ArraySeqs

  7. Hash Tables

  8. Weak Hash Maps

  9. Concurrent Maps

  10. Mutable Bitsets

Let’s cover some important mutable collection classes in this shot.

Array Buffers

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()

List Buffers

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()

StringBuilders

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

ArrayDeque is used for appending and prepending elements in a buffer. It uses a resizable array for this purpose.

Queues

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

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

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, O(1)O(1), 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()

RELATED TAGS

scala
mutable

CONTRIBUTOR

Sarvech Qadir
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring