This is a followup question to No Scala mutable list
I want to use a mutable list in Scala. I can chose from
For the sake of readers visiting this old question: The documentation's Concrete Mutable Collection Classes section has an overview of mutable list classes, including explanations on when to use which one.
I just want to use a list that I can add things to on the back.
Then choose something that implements Growable. I personally suggest one of the Buffer
implementations.
I stay away from LinkedList
and DoubleLinkedList
, as they are present mainly as underlying implementation of other collections, but have quite a few bugs up to Scala 2.9.x. Starting with Scala 2.10.0, I expect the various bug fixes have brought them up to standard. Still, they lack some methods people expect, such as +=
, which you'll find on collections based on them.
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.
If you want to append items you shouldn't use a List
at all. List
s are good when you want to prepend items. Use ArrayBuffer
instead.