TL ; DR:
add(i, x) puts x at index i. Use removeAt(i) to take out the item at index i. The other items move to make room or to close the gap.
val colors = mutableListOf("red", "green", "blue")
colors.add(1, "pink")
println(colors) // [red, pink, green, blue]
colors.removeAt(0)
println(colors) // [pink, green, blue]
Full lesson:
add(x) adds an item at the end. With an index first, add(i, x) puts x at index i instead. The items from index i on move one place to the right.
val pets = mutableListOf("Rex", "Milo")
pets.add(0, "Luna")
println(pets) // [Luna, Rex, Milo]
You met removeAt(i) in the last lesson. It takes out the item at index i. The items after it move one place to the left. It also returns the item:
val first = pets.removeAt(0)
println(first) // Luna
println(pets) // [Rex, Milo]
Watch the indexes. After an insert or a removal, the items behind that spot have new indexes.
Don't mix up removeAt and remove. On a list of numbers, remove(2) takes out the value 2, not index 2.
Your task
pets holds the pets waiting at the vet, in order.
Bella has an appointment, so she goes second, at index 1. Then Milo goes home. Take him out of the line.
The code below prints how many pets wait once Bella is in. At the end, it prints the pets left.
Expected output:
4
Rex Bella LunaFree plan: 30 tutor messages. PRO is unlimited.
