Start learning free

LESSON 113 OF 677 · ARRAYS I

Insert and Remove at a Position in Scala

Lesson

TL ; DR:

insert(i, x) puts x at index i. Use remove(i) to take out the item at index i. The other items move to make room or to close the gap.


val colors = scala.collection.mutable.ArrayBuffer("red", "green", "blue")

colors.insert(1, "pink")
println(colors)   // ArrayBuffer(red, pink, green, blue)

colors.remove(0)
println(colors)   // ArrayBuffer(pink, green, blue)


Full lesson:

+= adds an item at the end. To put one anywhere else in an ArrayBuffer, use insert(i, x). The items from index i on move one place to the right.

val pets = scala.collection.mutable.ArrayBuffer("Rex", "Milo")
pets.insert(0, "Luna")
println(pets)   // ArrayBuffer(Luna, Rex, Milo)

You met remove(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.remove(0)
println(first)   // Luna
println(pets)    // ArrayBuffer(Rex, Milo)

Watch the indexes. After an insert or a removal, the items behind that spot have new indexes.

Both take the index first. The -= operator is different: it takes out a value, not an index.


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 Luna
STEP 1 OF 2
    Ctrl + Enter to check