Task 5 of 11 · 0 solved · 11 to go0%
You can read the problem, but answers are checked only for signed-in students. Sign in to answer →

5.3 Lists — removing and replacing

Lesson

Changing what's in the list

Two more useful methods: remove(i) deletes the item at index i and shifts the rest left (so the list gets shorter), and set(i, value) replaces the item at index i without changing the size.


Worked example

ArrayList<String> names = new ArrayList<String>();
names.add("Ada");
names.add("Sam");
names.add("Bo");
names.remove(1);            // removes "Sam": now [Ada, Bo]
names.set(0, "Zoe");        // replaces index 0: now [Zoe, Bo]
System.out.println(names.get(0));   // Zoe
System.out.println(names.get(1));   // Bo
System.out.println(names.size());   // 2

▶ Try it: run this to remove and replace items. Change which index you remove or set, and re-run.



What does list.remove(1) do?


What does list.set(0, "Zoe") do?


The list is [Ada, Sam, Bo]. After remove(1), what does get(1) return?


True or false?


Type exactly what this program prints.

import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        ArrayList<Integer> list = new ArrayList<Integer>();
        list.add(1);
        list.add(2);
        list.set(0, 9);
        System.out.println(list);
    }
}