Collections
Vector Indexing
Read a value from a vector by index.
vector-indexing
A vector supports index reads. Index zero reads the first element.
Vector Indexing
VectorIndexing.scala
Replay: real traced execution (multi-file project)
object Main {
def main(args: Array[String]): Unit = {
val index = 1
val colors = Vector("red", "green", "blue")
val chosen = colors(index)
println("index=" + index)
println("chosen=" + chosen)
}
}
object Main {
def main(args: Array[String]): Unit = {
val index = 0
val colors = Vector("red", "green", "blue")
val chosen = colors(index)
println("index=" + index)
println("chosen=" + chosen)
}
}
object Main {
def main(args: Array[String]): Unit = {
val index = 2
val colors = Vector("red", "green", "blue")
val chosen = colors(index)
println("index=" + index)
println("chosen=" + chosen)
}
}
index ← 1, colors ← Vector(red, green, blue), chosen ← green
1object Main {2 def main(args: Array[String]): Unit = {3 val index→ 1 = 1 //@index=0, 24 val colors→ Vector(red, green, blue) = Vector("red", "green", "blue")5 val chosen→ green = colors(index)green67 println("index=" + index1)8 println("chosen=" + chosengreen)9 }10}outputindex=1 chosen=green
index ← 0, colors ← Vector(red, green, blue), chosen ← red
1object Main {2 def main(args: Array[String]): Unit = {3 val index→ 0 = 04 val colors→ Vector(red, green, blue) = Vector("red", "green", "blue")5 val chosen→ red = colors(index)red67 println("index=" + index0)8 println("chosen=" + chosenred)9 }10}outputindex=0 chosen=red
index ← 2, colors ← Vector(red, green, blue), chosen ← blue
1object Main {2 def main(args: Array[String]): Unit = {3 val index→ 2 = 24 val colors→ Vector(red, green, blue) = Vector("red", "green", "blue")5 val chosen→ blue = colors(index)blue67 println("index=" + index2)8 println("chosen=" + chosenblue)9 }10}outputindex=2 chosen=blue
Pick by Index
- The vector stores
red,green, andblue. - Scala indexes start at
0. indexis1.colors(index)selectsgreen. | Index | Color | Selected? | | --- | --- | --- | |0|red| no | |1|green| yes | |2|blue| no |
Exercise: VectorIndexing.scala
Pick one vector color by index and print the index and chosen color