ArrayList: A List That Grows

Arrays that can grow

An array has a fixed size. An ArrayList grows and shrinks as you add and remove items:

Think of it like this: An array is an egg box with exactly 6 holes. An ArrayList is a shopping bag – you can keep adding things.

import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        ArrayList<String> shopping = new ArrayList<>();
        shopping.add("milk");
        shopping.add("bread");
        shopping.add("eggs");
        System.out.println(shopping);
        System.out.println("Items: " + shopping.size());
        System.out.println("First: " + shopping.get(0));
    }
}

Output

[milk, bread, eggs]
Items: 3
First: milk

ArrayList<String> means “an ArrayList of Strings”. The type in the angle brackets < > says what the list holds.

The most useful ArrayList methods

MethodDoes
add(x)add x at the end
add(i, x)insert x at position i
get(i)the item at position i
set(i, x)replace the item at position i
remove(i) / remove(x)remove by position, or by value
size()how many items
contains(x)is x in the list?
indexOf(x)position of x, or -1
clear()remove everything
import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>();
        list.add("red");
        list.add("green");
        list.add("blue");
        list.add(1, "yellow");
        System.out.println(list);
        list.set(0, "pink");
        list.remove("green");
        System.out.println(list);
        System.out.println(list.contains("blue"));
        for (String colour : list) {
            System.out.println(colour.toUpperCase());
        }
    }
}

Output

[red, yellow, green, blue]
[pink, yellow, blue]
true
PINK
YELLOW
BLUE

Common mistake: A list's size is list.size() – not .length (arrays) or .length() (Strings).

HOME LABS COMMUNITY DASHBOARD