Task 1 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 — creating and adding

Lesson

A list that can grow

An array has a fixed size. An ArrayList is a resizable list: it starts empty and grows as you add items (and shrinks as you remove them). You say what type it holds in angle brackets, like ArrayList<String>, create it with new, and add with add(...). size() tells you how many items it holds.


Worked example

ArrayList<String> names = new ArrayList<String>();
names.add("Ada");
names.add("Sam");
System.out.println(names.size());   // 2
System.out.println(names.get(0));   // Ada

Each add appends to the end, so after two adds the size is 2.


▶ Try it: run this, then add more names or change them and re-run — the size follows.



How is an ArrayList different from an array?


After add("Ada") then add("Sam"), what is names.size()?


Fill the blank to add "Bo" to the list names.


True or false?


Type exactly what this program prints.

import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<String>();
        list.add("a");
        list.add("b");
        System.out.println(list.size());
        System.out.println(list);
    }
}