ArrayList

Reviewed & published by Brayan K

A plain array has a fixed size — once it's 5 elements long, it's always 5. Real programs rarely know the size in advance. ArrayList is a resizable list that grows and shrinks on demand, with friendly methods to add, find, and remove items.

Part of the free Java course at LearnCodingFast — hands-on lessons with worked examples and the output they print, plus practice exercises and a quick quiz.

What You'll Learn in This Lesson

1️⃣ Array vs ArrayList

An array is a fixed-size row of boxes. An ArrayList is a row of boxes that can add or remove boxes whenever you like.

String[] a = new String[3];
a[0] = "x";   // fixed at 3 slots
// a[3] = "y"; // crashes!

Size locked at creation.

ArrayList<String> a =
    new ArrayList<>();
a.add("x"); a.add("y");
a.add("z"); // grows freely

Grows and shrinks at runtime.

You need to import it: import java.util.ArrayList;. The part in angle brackets — the generic type — declares what the list holds, e.g. ArrayList<String> for text or ArrayList<Integer> for whole numbers.

import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        // An ArrayList grows and shrinks automatically — no fixed size.
        // The <String> says "this list holds Strings".
        ArrayList<String> todo = new ArrayList<>();

        todo.add("Buy milk");      // append to the end
        todo.add("Walk the dog");
        todo.add("Write code");
        System.out.println("List: " + todo);
        System.out.println("Size: " + todo.size());

        // Read by index (0-based, just like arrays)
        System.out.println("First: " + todo.get(0));

        // Insert at a position; everything after shifts right
        todo.add(1, "Make coffee");
        System.out.println("After insert: " + todo);

        // Replace an element
        todo.set(0, "Buy oat milk");
        System.out.println("After set: " + todo);

        // Remove by index OR by value
        todo.remove(2);                 // removes element at index 2
        todo.remove("Write code");      // removes the first matching value
        System.out.println("After removes: " + todo);
    }
}

2️⃣ The Methods You'll Use Daily

MethodWhat it does
add(x)Append x to the end
add(i, x)Insert x at index i
get(i)Read the element at index i
set(i, x)Replace the element at index i
remove(i) / remove(x)Delete by index or by value
size()Number of elements
contains(x)Is x in the list?
indexOf(x)Position of x, or -1
isEmpty()true if size is 0
clear()Remove everything
import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        ArrayList<Integer> scores = new ArrayList<>();
        scores.add(85);
        scores.add(92);
        scores.add(78);
        scores.add(90);

        // 1. The clean way: enhanced for-each loop
        int total = 0;
        for (int s : scores) {
            total += s;
        }
        double average = (double) total / scores.size();
        System.out.printf("Average: %.1f%n", average);

        // 2. Index loop, when you need the position
        for (int i = 0; i < scores.size(); i++) {
            System.out.println("Student " + (i + 1) + ": " + scores.get(i));
        }

        // Useful queries
        System.out.println("Contains 92? " + scores.contains(92));
        System.out.println("Index of 78: " + scores.indexOf(78));
        System.out.println("Is empty?   " + scores.isEmpty());
    }
}

3️⃣ Sorting With Collections

The java.util.Collections class provides static helpers that operate on any list:

Note the easy mix-up: Collections (helper methods) is a different class from Collection (the interface all collections implement).

import java.util.ArrayList;
import java.util.Collections;

public class Main {
    public static void main(String[] args) {
        // A waiting list that we keep sorted and trim as people are seated.
        ArrayList<String> waitlist = new ArrayList<>();
        waitlist.add("Zoe");
        waitlist.add("Amir");
        waitlist.add("Mia");
        waitlist.add("Ben");

        // Sort alphabetically (Collections has list helpers)
        Collections.sort(waitlist);
        System.out.println("Sorted: " + waitlist);

        // Seat the first two guests
        System.out.println("Seating: " + waitlist.get(0) + ", " + waitlist.get(1));
        waitlist.remove(0);
        waitlist.remove(0);   // index 0 again — the list shifted down
        System.out.println("Still waiting: " + waitlist);

        // Reverse the remaining order
        Collections.reverse(waitlist);
        System.out.println("Reversed: " + waitlist);

        // Clear everyone out
        waitlist.clear();
        System.out.println("After clear, empty? " + waitlist.isEmpty());
    }
}
import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        // 🎯 YOUR TURN — replace each ___ using the hint beside it.

        List<String> jobs = new ArrayList<>();
        jobs.add("print");
        jobs.add("scan");
        jobs.add("fax");

        System.out.println("Jobs: " + jobs);

        // 1) Read by position. Positions start at 0, not 1.
        System.out.println("First: " + jobs.___(0));        // 👉 replace ___ with get

        // 2) Is this value in the list at all?
        System.out.println("Has fax? " + jobs.___("fax"));  // 👉 replace ___ with contains

        // 3) Where is it? -1 would mean "nowhere".
        System.out.println("Where is scan? " + jobs.___("scan"));  // 👉 replace ___ with indexOf

        // 4) Replace what is already at position 2 — this does not insert.
        jobs.___(2, "email");                                // 👉 replace ___ with set

        // Two arguments to add() INSERTS and shifts everything right.
        jobs.add(1, "copy");
        System.out.println("Now: " + jobs);

        // 5) A String argument removes that value; an int removes that POSITION.
        jobs.___("copy");                                    // 👉 replace ___ with remove
        jobs.remove(0);
        System.out.println("After removals: " + jobs);
        System.out.println("Empty? " + jobs.isEmpty() + ", size " + jobs.size());
    }
}

🧩 Reorder Challenge

Reorder these lines to create a list of two colors and print its size.

colors.add("red");
System.out.println(colors.size());
ArrayList<String> colors = new ArrayList<>();
colors.add("blue");
ArrayList<String> colors = new ArrayList<>();
colors.add("red");
colors.add("blue");
System.out.println(colors.size());

Why: The list must be created before anything can be added to it, and both add calls must run before size() reports the count. Output: 2.

🧠 Quick Recall

1. What does this print?

ArrayList<String> a = new ArrayList<>();
a.add("x");
a.add(0, "y");
System.out.println(a);

[y, x]. add(0, "y") inserts "y" at index 0, pushing "x" to index 1.

2. What does this print?

ArrayList<Integer> n = new ArrayList<>();
n.add(10); n.add(20); n.add(30);
n.remove(1);
System.out.println(n);

[10, 30]. remove(1) deletes the element at index 1 (the value 20), not the value 1.

3. What does indexOf return for a value that isn't present?

-1. That's the universal "not found" sentinel; check contains first if you only need a yes/no.

Common Beginner Mistakes

📋 Quick Reference

MethodDescriptionExample
new ArrayList<>()Create an empty listArrayList<String> l = new ArrayList<>();
add(e)Append to the endl.add("x")
add(i, e)Insert at index il.add(0, "y")
get(i)Read element at index il.get(0)
set(i, e)Replace element at index il.set(0, "z")
remove(i)Delete element at index il.remove(1)
remove(e)Delete first matching valuel.remove("x")
size()Number of elementsl.size()
contains(e)Is e in the list?l.contains("x")
indexOf(e)Position of e, or -1l.indexOf("x")
isEmpty()true when size is 0l.isEmpty()
clear()Remove every elementl.clear()
for (T e : l)Loop over every elementfor (String s : l)
Collections.sort(l)Sort ascending in placeCollections.sort(l)
List.of(...)Fixed, immutable list literalList.of("a", "b")

🎉 Lesson Complete!

You can now use Java's workhorse collection: create a generic ArrayList, add/get/set/remove elements, query it with size/contains/indexOf, loop with for-each, and sort or reverse with Collections. You also know the remove(index) vs remove(value) trap.

Practice quiz

What is the key advantage of an ArrayList over a plain array?

  • It is always faster
  • It can hold primitives directly
  • It grows and shrinks automatically
  • It needs no import

Answer: It grows and shrinks automatically. An ArrayList resizes automatically, unlike a fixed-size array.

Which is the correct way to declare a list of whole numbers?

  • ArrayList<Integer>
  • ArrayList<int>
  • ArrayList<number>
  • ArrayList[int]

Answer: ArrayList<Integer>. Lists hold objects, so use the wrapper Integer, not the primitive int.

Given a list [10, 20, 30], what does remove(1) do?

  • Removes the value 1
  • Removes the first element
  • Throws an error
  • Removes the element at index 1 (the 20)

Answer: Removes the element at index 1 (the 20). remove(int) removes by index, so remove(1) deletes index 1 (the value 20), leaving [10, 30].

After: list has ['x']; then list.add(0, 'y'); what is the list?

  • [x, y]
  • [y, x]
  • [y]
  • [x]

Answer: [y, x]. add(0, 'y') inserts 'y' at index 0, pushing 'x' to index 1, giving [y, x].

What does indexOf(value) return when the value is not present?

  • -1
  • 0
  • null
  • It throws

Answer: -1. indexOf returns -1, the universal 'not found' sentinel.

Which import is required to use ArrayList?

  • import java.util.List;
  • import java.lang.ArrayList;
  • import java.util.ArrayList;
  • No import needed

Answer: import java.util.ArrayList;. ArrayList lives in java.util, so you import java.util.ArrayList.

Which method sorts a list into ascending order?

  • list.sort()
  • Collections.sort(list)
  • Arrays.sort(list)
  • list.order()

Answer: Collections.sort(list). Collections.sort(list) sorts a list ascending (the lesson uses it).

What does the diamond <> in 'new ArrayList<>()' mean?

  • An empty list literal
  • A wildcard
  • A primitive marker
  • Java infers the type from the left side

Answer: Java infers the type from the left side. The diamond lets Java infer the type already declared on the left.

Which method tells you whether a value exists in the list?

  • has(x)
  • contains(x)
  • exists(x)
  • find(x)

Answer: contains(x). contains(x) returns true if x is in the list.

The Collections class (helper methods) is the same as the Collection interface.

  • True
  • Only for lists
  • False
  • Only with generics

Answer: False. Collections (with an s) is the helper class; Collection is the interface — different things.

Continue this course

Frequently asked questions

What is the difference between an array and an ArrayList?

A plain array has a fixed length set at creation — int[] a = new int[5] is always size 5. An ArrayList grows and shrinks automatically as you add and remove elements, and it provides handy methods like add, remove, contains, and indexOf. Arrays are slightly faster and can hold primitives directly; ArrayList holds objects and is far more convenient for collections that change size.

Why do I write ArrayList<Integer> instead of ArrayList<int>?

ArrayList can only store objects, not primitives, so you use the wrapper class Integer instead of int (and Double instead of double, Boolean instead of boolean). Thanks to autoboxing, you can still write list.add(5) and Java automatically wraps the int 5 into an Integer, and unwraps it back when you read it.

What does the diamond <> in new ArrayList<>() mean?

It is the diamond operator. Because you already declared the type on the left (ArrayList<String> names = ...), Java can infer the same type on the right, so you write new ArrayList<>() instead of repeating new ArrayList<String>(). It is just a shorthand that reduces repetition.

Should I use remove(index) or remove(value)?

remove(int index) deletes the element at that position; remove(Object value) deletes the first element equal to that value. This is a famous trap with ArrayList<Integer>: remove(2) removes index 2, while remove(Integer.valueOf(2)) removes the value 2. Be explicit about which you mean when the list holds Integers.

How do I loop over an ArrayList?

Use the enhanced for-each loop for read-only iteration: for (String name : names) { ... }. Use an index loop, for (int i = 0; i < list.size(); i++), when you need the position or plan to modify the list. Never modify a list with add or remove inside a for-each loop — that throws a ConcurrentModificationException; use an Iterator or a reverse index loop instead.