 |  |  | An Overview of the Collections API | Contents |
An Overview of the Collections API
Collection hierarchy
The most important collection classes are shown in the figure
above.
There is quite a bit of commonality
shared by all these classes. For instance, every kind of collection can be created by the same
uniform syntax, writing the collection class name followed by its elements:
Traversable(1, 2, 3) |
Iterable("x", "y", "z") |
Map("x" -> 24, "y" -> 25, "z" -> 26) |
Set(Color.red, Color.green, Color.blue) |
SortedSet("hello", "world") |
Buffer(x, y, z) |
IndexedSeq(1.0, 2.0) |
LinearSeq(a, b, c)
|
The same principle also applies for specific collection implementations, such as:
List(1, 2, 3) |
HashMap("x" -> 24, "y" -> 25, "z" -> 26)
|
All these collections get displayed with toString in the same way they are
written above.
All collections support the API provided by Traversable, but
specialize types wherever this makes sense. For instance the map
method in class Traversable returns another Traversable as its
result. But this result type is overridden in subclasses. For
instance, calling map on a List yields again a List, calling
it on a Set yields again a Set and so on.
scala> List(1, 2, 3) map (_ + 1) |
res0: List[Int] = List(2, 3, 4) |
scala> Set(1, 2, 3) map (_ * 2) |
res0: Set[Int] = Set(2, 4, 6)
|
This behavior which is
implemented everywhere in the collections libraries is called the uniform return type principle.
Most of the classes in the collections hierarchy exist in three
variants: root, mutable, and immutable. The only exception is the
Buffer trait which only exists as a mutable collection.
In the following, we will review these classes one by one.
Next: Trait Traversable
 |  |  | An Overview of the Collections API | Contents |