Which scala mutable list to use?

后端 未结 4 1062
梦如初夏
梦如初夏 2020-12-13 13:33

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
相关标签:
4条回答
  • 2020-12-13 13:49

    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.

    0 讨论(0)
  • 2020-12-13 13:58

    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.

    0 讨论(0)
  • 2020-12-13 14:09

    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 MutableLists which support efficient append, and mutable.Queues.

    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.

    0 讨论(0)
  • 2020-12-13 14:16

    If you want to append items you shouldn't use a List at all. Lists are good when you want to prepend items. Use ArrayBuffer instead.

    0 讨论(0)
提交回复
热议问题