See more here
|Fixed length seq. Mutable in elements but not in length|
|Fixed length seq. Immutable both in elements and length. Internally as a 32-branch tree. Default for |
|Variable length seq. Mutable both in elements and length. Efficient to append.|
|Internal list. Efficient prepend and append on both ends.|
|Mutable and immutable map implemented as hash trie|
|dict||Both mutable and immutable|
|Immutable RB tree map|
|Mutable RB tree map|
The underlying implementation is best described here for mutable collection and for immutable collection.
Vector(1, 2, 3)
collection.mutable.ArrayBuffer(1, 2, 3)
List(1, 2, 3)
collection.mutable.ListBuffer(1, 2, 3)
Set(1, 2, 3)
collection.mutable.Set(1, 2, 3)
Immtable collection is optimized based on the agreement that both the size and the content cannot be changed, whereas mutable collection allows changes in both the size and the content.
Array is something in between: you can change the content but not the size. Therefore, in some sense
Array is mutable, but due to the underlying data structure, changes in size are natually not allowed. People are arguing on this point. The definition of mutability in the official document is that “A mutable collection can be updated or extended in place.” So logically, if any change can be made after the object being created, it is mutable. But, really, it doesn’t matter much.
var for an immutable collection allows operations such as
+=. But what’s under the hood is that a new immutable collection is being created and attached to the same reference. The old one is then recycled. In this case, you still cannot modify values.
scala var x = Map("AL" -> "Alabama") // still default immutable.Map x += ("CA"->"California") // okay because a new map is being generated x("CA") = "Air China" // illegal because of an attempt of modifying values
val m = Map(1->"a") val tm = collection.immutable.TreeMap(m.toArray:_*)
The best way to choose a proper collection type is to look at the complexity of operations being used in your applications. This perhaps is also the easist way to figure out the underlying implementation and data structure.
The official document provides an excellent summary of the performance characteristics for each Scala collection class.