This is a followup question to No Scala mutable list
I want to use a mutable list in Scala. I can chose from
scala.collection.mutable.DoubleLinkedList
scala.collection.mutable.LinkedList
scala.collection.mutable.ListBuffer
scala.collection.mutable.MutableList
Which is nice, but what is the "standard", recommended, idiomatic scala way? I just want to use a list that I can add things to on the back.
In my case, I am using a HashMap, where the "lists" (I am meaning it in general sense) will be on value side. Then, I am reading something from a file and for every line, I want to find the right list in the hashmap and append the value to the list.
Depends what you need.
DoubleLinkedList
is a linked list which allows you to traverse back-and-forth through the list of nodes. Use its prev
and next
references to go to the previous or the next node, respectively.
LinkedList
is a singly linked list, so there are not prev
pointers - if you only traverse to the next element of the list all the time, this is what you need.
EDIT: Note that the two above are meant to be used internally as building blocks for more complicated list structures like MutableList
s which support efficient append, and mutable.Queue
s.
The two collections above both have linear-time append operations.
ListBuffer
is a buffer class. Although it is backed by a singly linked list data structure, it does not expose the next
pointer to the client, so you can only traverse it using iterators and the foreach
.
Its main use is, however, as a buffer and an immutable list builder - you append elements to it via +=
, and when you call result
, you very efficiently get back a functional immutable.List
. Unlike mutable and immutable lists, both append and prepend operations are constant-time - you can append at the end via +=
very efficiently.
MutableList
is used internally, you usually do not use it unless you plan to implement a custom collection class based on the singly linked list data structure. Mutable queues, for example, inherit this class. MutableList
class also has an efficient constant-time append operation, because it maintains a reference to the last node in the list.