Thuta Learning
Java
AdvancedProgrammingBeginner

ArrayList

JavaLesson 2725 min

What you'll walk away with

  • Explain the difference between an array (fixed size) and an ArrayList (resizable)
  • Use add, add(index, item), get, set, remove, contains, indexOf and size and predict the result
  • Understand why the element type is Integer rather than int, and how remove(int) differs from remove(Object)
  • Remove items during iteration safely with removeIf or an Iterator
  • Return a read-only copy with List.copyOf instead of exposing an internal list

Explain it simply

Explain it simply

Think of an array as an egg carton with exactly twelve slots: to store a thirteenth egg you must buy a new carton and move everything. An ArrayList is more like a stretchy bag that grows as you add items and closes the gap when you take one out.

An ArrayList keeps items in the order you added them, starting at index 0. It is the collection Java developers reach for most often whenever they cannot know the number of items in advance, as with a todo list, a shopping cart or search results.

Problem → Why → Solution

The problem: arrays have a fixed size

If you store tasks in a String[] array, you must choose its size when you create it. The code below has only two slots, so adding a third task throws ArrayIndexOutOfBoundsException. Removing a task means shifting the later items yourself and tracking how many slots are really in use with a separate count variable.

When people first switch to ArrayList, array habits also make them write tasks.length, which is a compile error because ArrayList has no length field.

Main.java
public class Main {
  public static void main(String[] args) {
    String[] tasks = new String[2];
    int count = 0;
    tasks[count++] = "Learn Java syntax";
    tasks[count++] = "Practice loops";
    tasks[count++] = "Build mini project"; // ArrayIndexOutOfBoundsException: 2
    System.out.println(count + " tasks");
  }
}

Why do we need ArrayList?

A Java array's length never changes after it is created. ArrayList uses an array internally too, but when it runs out of room it automatically creates a bigger array and copies the items across. When you remove an item from the middle it shifts the later items for you, and size() always reports the real number of items.

Core concept: a growable array inside

ArrayList<String> uses a generic type to say "a list that holds only Strings". The type argument must be a reference type, so ArrayList<int> does not compile; you write ArrayList<Integer> with the wrapper class. When you call list.add(5), Java converts the int 5 into an Integer object automatically, which is called autoboxing, and converts it back when you read it, which is unboxing. Declaring the variable with the interface type, List<String> tasks = new ArrayList<>();, is good practice, and the <> diamond saves you from repeating the type on the right.

Internally an ArrayList holds an Object[] array plus a size counter. The array's length is called the capacity, while size() is the number of items actually stored. When the capacity is full, it allocates a bigger array and copies every item over (OpenJDK grows it by roughly 1.5 times, but that is an implementation detail). Because the copy happens only occasionally, adding at the end is fast on average.

Because it is backed by an array, get(index) and set(index, value) are instant no matter how many items there are. Inserting or removing at the front or in the middle, as with add(0, item) or remove(0), has to shift every later item by one slot, so it slows down as the list grows. contains() and indexOf() also scan from the start using equals(), so they are slow on long lists. Because they use equals(), two different String objects with the same text count as a match, while your own classes need an equals() override for these methods to behave.

Valid indexes run from 0 to size() - 1. Reading outside that range, such as get(size()), throws IndexOutOfBoundsException. ArrayList's toString() prints the [a, b, c] form, which makes debugging easy.

Mental model: capacity versus size
  1. Inside: an array plus a size count
  2. add() fills the next free slot
  3. Full? Copy into a bigger array
  4. Middle insert/remove shifts items

Reading by index is cheap; changing the front or middle costs a shift.

General pattern

java
List<Type> list = new ArrayList<>();
list.add(item);              // append at the end
list.add(index, item);       // insert, shifting the rest right
Type value = list.get(index);
list.set(index, newItem);    // replace
list.remove(index);          // or list.remove(object)
boolean found = list.contains(item);
int count = list.size();

Declare the variable with the List interface and create it as an ArrayList. add() appends, and add(index, item) inserts in between. get and set read and replace by index, remove() comes in an index version and an object version, and size() is the item count.

Example: editing a task list

This example edits a task list with the everyday ArrayList operations: adding to the end, inserting in the middle, removing by value, replacing and searching. Write down what the list looks like after each line, then compare your notes with the output.

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

public class Main {
  public static void main(String[] args) {
    List<String> tasks = new ArrayList<>();
    tasks.add("Learn Java syntax");
    tasks.add("Practice loops");
    tasks.add("Build mini project");
    tasks.add(1, "Read the docs");        // insert at index 1, shifts the rest right

    tasks.remove("Practice loops");       // remove by value
    tasks.set(0, "Review Java syntax");   // replace the item at index 0

    System.out.println(tasks);
    System.out.println("First task: " + tasks.get(0));
    System.out.println("Total tasks: " + tasks.size());
    System.out.println("Has docs task: " + tasks.contains("Read the docs"));
    System.out.println("Index of project: " + tasks.indexOf("Build mini project"));
  }
}

Code breakdown

  1. Line 6List<String> tasks = new ArrayList<>();

    Creates an empty list that only accepts Strings. Because the variable's type is List, switching implementations later only changes the right-hand side.

  2. Line 10tasks.add(1, "Read the docs"); // insert at index 1, shifts the rest right

    Inserting at index 1 pushes "Practice loops" and "Build mini project" one slot to the right, giving [Learn Java syntax, Read the docs, Practice loops, Build mini project].

  3. Line 12tasks.remove("Practice loops"); // remove by value

    A String argument selects the remove(Object) version, which removes the first item that is equals() to it and returns true if it found one.

  4. Line 13tasks.set(0, "Review Java syntax"); // replace the item at index 0

    set() replaces the item at index 0 without changing the size, and returns the old item.

  5. Lines 15-19System.out.println("Index of project: " + tasks.indexOf("Build mini project"));

    The final list has three items. contains() returns true and indexOf() returns 2; when nothing matches it returns -1.

You should see
[Review Java syntax, Read the docs, Build mini project]
First task: Review Java syntax
Total tasks: 3
Has docs task: true
Index of project: 2

The remove(int) versus remove(Object) trap

On a List<Integer>, the two remove() overloads cause confusion. ids.remove(1) picks remove(int index), which matches the int argument exactly, so it removes the item at index 1 rather than the value 1. To remove the value, pass it as an object with Integer.valueOf(1).

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

public class Main {
  public static void main(String[] args) {
    List<Integer> ids = new ArrayList<>(List.of(5, 1, 7, 1));

    ids.remove(1);                    // remove(int index): removes the 1 at index 1
    System.out.println(ids);          // [5, 7, 1]

    ids.remove(Integer.valueOf(1));   // remove(Object): removes the value 1
    System.out.println(ids);          // [5, 7]

    int total = 0;
    for (int id : ids) {              // auto-unboxing Integer -> int
      total += id;
    }
    System.out.println("Total: " + total);
  }
}

Removing safely while iterating

Calling list.remove() inside a for-each loop makes the ArrayList's iterator notice the change and throw ConcurrentModificationException. The check is fail-fast but only best-effort, so in some cases you instead get a silently skipped item. To remove by a condition, use removeIf(), or call iterator.remove() on an explicit Iterator. A list created with List.of() is immutable, so add or remove on it throws UnsupportedOperationException.

Main.java
import java.util.ArrayList;
import java.util.ConcurrentModificationException;
import java.util.List;

public class Main {
  public static void main(String[] args) {
    List<String> names = new ArrayList<>(List.of("Aye", "", "Bo", "", "Chit"));

    try {
      for (String name : names) {
        if (name.isEmpty()) names.remove(name);   // modifies the list mid-loop
      }
    } catch (ConcurrentModificationException e) {
      System.out.println("for-each + remove: ConcurrentModificationException");
    }

    names.removeIf(String::isEmpty);              // safe bulk removal
    System.out.println(names);

    List<String> fixed = List.of("x", "y");
    try {
      fixed.add("z");
    } catch (UnsupportedOperationException e) {
      System.out.println("List.of is immutable");
    }
  }
}

In real projects

Where this shows up in real projects

Rows returned by a database query, item arrays from a JSON API, products in a shopping cart and lists of notifications are all handled in Java code as List<T>, and most of them are ArrayLists. Libraries such as Spring Data JPA return List<Order> from repository methods, and JSON libraries such as Jackson turn a JSON array into an ArrayList.

If a class returns its internal list straight from a getter, outside code can add or remove items and bypass the object's rules. That is why classes return a read-only copy or view with List.copyOf(items) or Collections.unmodifiableList(items). When you know roughly how many items are coming, new ArrayList<>(expectedSize) sets the capacity up front and avoids repeated copying. For queue-like work that constantly adds and removes at the front, a collection such as ArrayDeque fits better.

Common mistakes

Common mistakes

1. Using length or length() on a list

Arrays use tasks.length (a field) and Strings use name.length() (a method), but collections use tasks.size(). Calling length on an ArrayList is a "cannot find symbol" compile error.

2. Expecting remove(1) to remove the value 1

On a List<Integer> scores, scores.remove(1) removes the item at index 1. On a short list you get IndexOutOfBoundsException; on a longer one the wrong item silently disappears. Write scores.remove(Integer.valueOf(1)) to remove the value.

3. Adding or removing inside a for-each

Changing the list inside a for-each loop typically throws ConcurrentModificationException. Use removeIf(), Iterator.remove(), or collect the results into a new list.

4. Trying to modify a List.of() result

List.of("a", "b") is immutable, so add() throws UnsupportedOperationException. Copy it with new ArrayList<>(List.of(...)) when you need to change it.

Best practices

Best practices

  • Declare variables, parameters and return types as List rather than ArrayList.
  • Use List.of() for fixed data that never changes, and ArrayList only for lists you need to modify.
  • When removing a value from a List<Integer>, write Integer.valueOf() explicitly and add a comment so readers are not confused.

Mini challenge

Mini challenge: exam score list

Remove the mistyped value 1 from a score ArrayList, then write one method that returns a read-only list of scores at or above the pass mark (50) and another that computes the average. The original list must stay unchanged.

  • Remove the value 1, not the item at index 1
  • passingScores() must not touch its input; it uses removeIf on a copy
  • passingScores() returns a read-only list via List.copyOf()
  • average() returns 0 for an empty list and is printed with one decimal place
  • Try add() on the read-only list and catch the exception
Main.java
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

public class Main {
  static List<Integer> passingScores(List<Integer> scores, int passMark) {
    // TODO: copy the input, removeIf below passMark, return a read-only copy
    return null;
  }

  static double average(List<Integer> scores) {
    // TODO: return 0 for an empty list, otherwise total / size as a double
    return 0;
  }

  public static void main(String[] args) {
    List<Integer> scores = new ArrayList<>(List.of(72, 45, 90, 1, 58));
    // TODO: remove the VALUE 1, print scores, passing scores, and the average
    // TODO: show that the passing list cannot be modified
  }
}

Expected: The program should print: Scores: [72, 45, 90, 58] Passing: [72, 90, 58] Original untouched: 4 scores Average: 73.3 Passing list is read-only

Show hint

remove(Integer.valueOf(1)) removes the value. Cast with (double) total / scores.size() to avoid integer division, and use String.format(Locale.ROOT, "%.1f", value) so the decimal separator does not depend on the machine's locale.

Show solution
Main.java
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

public class Main {
  static List<Integer> passingScores(List<Integer> scores, int passMark) {
    List<Integer> result = new ArrayList<>(scores);
    result.removeIf(score -> score < passMark);
    return List.copyOf(result);
  }

  static double average(List<Integer> scores) {
    if (scores.isEmpty()) {
      return 0;
    }
    int total = 0;
    for (int score : scores) {
      total += score;
    }
    return (double) total / scores.size();
  }

  public static void main(String[] args) {
    List<Integer> scores = new ArrayList<>(List.of(72, 45, 90, 1, 58));
    scores.remove(Integer.valueOf(1)); // the value 1 was a typo, not index 1
    System.out.println("Scores: " + scores);

    List<Integer> passing = passingScores(scores, 50);
    System.out.println("Passing: " + passing);
    System.out.println("Original untouched: " + scores.size() + " scores");
    String avg = String.format(Locale.ROOT, "%.1f", average(passing));
    System.out.println("Average: " + avg);

    try {
      passing.add(100);
    } catch (UnsupportedOperationException e) {
      System.out.println("Passing list is read-only");
    }
  }
}

Quick quiz 1 / 3

After List<String> l = new ArrayList<>(List.of("a", "b", "c")); l.add(1, "x"); l.remove("b");, what does System.out.println(l) print?

Quick quiz 2 / 3

After List<Integer> n = new ArrayList<>(List.of(10, 20, 30)); n.remove(1);, what is n?

Quick quiz 3 / 3

Which is the safest and simplest way to remove blank strings from a list?

What to remember

  • ArrayList stores items in an internal array and copies them into a bigger one when it fills up, so its size is not fixed.
  • get and set are fast; inserting or removing at the front or middle shifts items and is slower.
  • The item count is size(), the element type must be Integer rather than int, and on a List<Integer> watch remove(int) versus remove(Object).
  • Use removeIf() to remove during iteration, and hand out read-only copies with List.copyOf().

Java SE 25 API Specification — Oracle

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.