Vector and Array
The coach wants to look up and correct paces anywhere in the season's log: the 40th run, the 212th, the last. A List would walk its chain every time. Scala has two sequences built for jumping straight to a position, and they differ in one big way.
The rule
Vector: immutable and fast anywhere. Array: mutable, fixed size, Java's own.
A Vector is immutable like a List, but stores its elements in a wide, shallow tree, so reading or replacing any position takes about the same short time:
val paces = Vector(306, 312, 298, 301) // seconds per km
paces(2) // 298
val corrected = paces.updated(1, 305) // Vector(306, 305, 298, 301)
paces // unchanged: Vector(306, 312, 298, 301)For an immutable sequence that you read by position, Vector is the usual default.
An Array is a fixed-size block of slots, exactly a Java array. It is mutable: you can overwrite a slot in place, even through a val:
val lapTimes = Array(71, 69, 74) // seconds per lap
lapTimes(0) = 70 // allowed: now 70, 69, 74
lapTimes.length // 3, and it can never growArrays are the fastest option and are what many Java libraries expect, but they bring two Java habits that surprise people:
- Equality is identity.
Array(1, 2) == Array(1, 2)isfalse, because they are two separate objects. Usea.sameElements(b)to compare contents. - Printing is unhelpful.
println(lapTimes)shows something like[I@1b6d3586. UselapTimes.mkString(", ")to see70, 69, 74.
The shortcut
Pick with two questions: Must it change in place? Do I need fast access by position?
- No changes in place, walked from the front: List.
- No changes in place, read at any position: Vector.
- Changed in place, fixed size, raw speed or a Java library: Array.
Choose the type
The paces are read and corrected by position, but should never change behind anyone's back: Vector.
Drills
Answer fast — trust the rule.
What is Vector(306, 312, 298, 301).updated(1, 305)?
val lapTimes = Array(71, 69, 74) then lapTimes(0) = 70. What happens?
What is Array(1, 2) == Array(1, 2)?
Which type fits an immutable season log that is read at random positions?
How do you print an array's contents readably?
Remember
- A Vector is immutable and fast at any position; an Array is mutable, fixed in size, and Java's own type.
- Choose with two questions: must it change in place, and do you need access by position?
- Trap: Arrays compare and print like Java objects, so use
sameElementsandmkString.
