ArrayList: your default List

Collections · lesson 2 of 42 · 3 min read

Use ArrayList confidently: add, get, set, remove, copy, and pre-size it.

Open this lesson in the learning hub

Key points

  • ArrayList wraps a plain array. Index access is instant; it grows by copying into a bigger array when full.
  • add(e) appends. add(i, e) inserts and shifts everything after it right — cheap at the end, costly at the front.
  • get, set, size, indexOf, contains cover almost every real use.
  • If you know the rough size, pass it: new ArrayList<>(1000) avoids repeated regrow copies.
  • new ArrayList<>(other) makes an independent list. Changing the copy leaves the original alone.

Example

import java.util.*;

public class Main {
    public static void main(String[] args) {
        List<String> langs = new ArrayList<>();
        langs.add("Java");
        langs.add("Kotlin");
        langs.add(1, "Scala");

        System.out.println("list              : " + langs);
        System.out.println("size              : " + langs.size());
        System.out.println("get(0)            : " + langs.get(0));
        System.out.println("indexOf(Kotlin)   : " + langs.indexOf("Kotlin"));
        System.out.println("contains(Groovy)  : " + langs.contains("Groovy"));

        langs.set(0, "Java 21");
        langs.remove("Scala");
        System.out.println("after set + remove: " + langs);

        List<String> copy = new ArrayList<>(langs);
        copy.clear();
        System.out.println("copy cleared      : " + copy);
        System.out.println("original untouched: " + langs);

        List<String> big = new ArrayList<>(1000);
        for (int i = 0; i < 5; i++) big.add("item" + i);
        System.out.println("presized list     : " + big);
    }
}

Reach for ArrayList first. Only move away when you can name the reason.

This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Collections course, and every lesson in it is listed on the Collections contents page.