Start learning free

LESSON 111 OF 671 · ARRAYS I

Insert and Remove at a Position in Java

Lesson

TL ; DR:

add(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.


List<String> colors = new ArrayList<>(List.of("red", "green", "blue"));

colors.add(1, "pink");
// colors is now [red, pink, green, blue]

colors.remove(0);
// colors is now [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.

List<String> pets = new ArrayList<>(List.of("Rex", "Milo"));

pets.add(0, "Luna");
// pets is now [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:

String first = pets.remove(0);
// first is "Luna", and pets is now [Rex, Milo]

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

Careful with lists of numbers. On a List<Integer>, remove(2) still takes out index 2. To take out the value 2, write remove(Integer.valueOf(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 Luna
STEP 1 OF 2
    Ctrl + Enter to check