Start learning free

LESSON 116 OF 677 · ARRAYS I

Slicing an ArrayList in Kotlin

Lesson

TL ; DR:

list.subList(i, j) gives the items from index i up to, not including, j. The original list doesn't change.


val letters = mutableListOf("a", "b", "c", "d", "e")

val middle = letters.subList(1, 4)
println(middle)    // [b, c, d]

println(letters)   // [a, b, c, d, e]


Full lesson:

Sometimes you need only part of a list, like the first few items. The subList method gives you that part.

Give it the start index and the end index. The item at the end index is not included. So letters.subList(1, 4) has the items at 1, 2 and 3.

That makes the length easy to see: 4 - 1 = 3 items.

To go to the very end, use the size as the end index:

val tail = letters.subList(3, letters.size)
println(tail)   // [d, e]

Taking a sub-list leaves the original as it was.

But subList doesn't copy the items. It shows the original's items, so changing one changes the other. Call toMutableList() on it when you need a separate copy.


Your task

runners holds a race's runners, in the order they finished.

Put the first three in a new ArrayList named podium. Put everyone else, from index 3 to the end, in one named rest.

The code below prints both, then the length of runners.

Expected output:

Ana Ben Cleo
Dan Eve
5
STEP 1 OF 2
    Ctrl + Enter to check