ArrayList: A Growable List

Add, insert, read, replace and remove items, and watch later items shift as the list changes.

Java · intermediate · 7 min · 11 steps · free

What you'll learn

ArrayListDemo.java

import java.util.ArrayList;
import java.util.List;

public class ArrayListDemo {
    public static void main(String[] args) {
        List<String> todo = new ArrayList<>();
        todo.add("email");
        todo.add("shop");
        todo.add(1, "call");          // insert at index 1: later items shift right
        String first = todo.get(0);
        todo.set(2, "groceries");     // replace an item
        todo.remove("email");         // later items shift left
        boolean hasCall = todo.contains("call");
        int size = todo.size();
        System.out.println(todo + " " + first + " " + hasCall + " " + size);
    }
}

Step by step

  1. An empty ArrayList, declared as the List interface.
  2. "email" is added to the end of the ArrayList that todo points to.
  3. "shop" is added to the end of the ArrayList that todo points to.
  4. add(1, "call") inserts at index 1; "shop" shifts to index 2.
  5. get(0) reads by index.
  6. set(2, …) replaces the item at index 2.
  7. remove("email") takes out that item; everything after it moves left one place.
  8. hasCall is created on the stack with the value true.
  9. size is created on the stack with the value 2.
  10. It prints [call, groceries] email true 2.
  11. [call, groceries]: an ArrayList grows and shrinks, keeping items in order by index.

Common mistakes

Best practices

Key takeaways

Check yourself

list = [a, b, c]; list.add(0, "z"). list.get(1)?

Answer: "a". Everything shifted right by one.

Which is faster on an ArrayList?

Answer: get(i). Reading by index is instant; inserting at the front shifts everything.

More in The Collections Framework