Java ArrayList

Beginner
8 min read
Updated: Nov 2026
3 examples
java.util.ArrayList

Definition and Usage

In Java, ArrayList (in java.util, since Java 1.2) is an ordered list backed by a resizable array. Every element has an index: the first is at 0 and the last at size() - 1. You can read or replace any element by index in constant time with get() and set(), and the list grows by itself when you add() more elements than it has room for.

It implements List, Collection, and Iterable, plus the marker interfaces RandomAccess, Cloneable, and Serializable. An ArrayList keeps elements in the order you add them, allows duplicates, and allows null. The ArrayList Methods index lists every guide.

Two rules to remember.

An ArrayList is not thread-safe: share it between threads only with your own locking or a wrapper such as Collections.synchronizedList. And its iterators are fail-fast: if the list is structurally changed while you loop over it (other than through the iterator itself), the loop usually stops with ConcurrentModificationException. Use removeIf() or iterator().remove() to delete while looping.

Java Syntax

Import the class, then create a list. Declaring the variable as List keeps your code flexible:

Java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

List<String> names = new ArrayList<>();                      // empty
List<Integer> nums = new ArrayList<>(100);                   // room for 100, size 0
List<String> copy = new ArrayList<>(Arrays.asList("a", "b")); // [a, b]

names.add("x");                    // [x]
names.add(0, "w");                 // [w, x]
System.out.println(names.get(1));  // x  (index starts at 0)

The number in new ArrayList<>(100) is a starting capacity (room in the internal array), not a size. A list made with new ArrayList<>() starts with no room at all and, in current JDKs, allocates space for 10 elements on the first add, then grows by about half each time it fills up. Those numbers are implementation details; the methods ensureCapacity() and trimToSize() let you influence them.

ArrayList vs Array, LinkedList, and ArrayDeque

All four keep elements in order, but they suit different jobs:

TypeGood forKeep in mind
String[], int[]A fixed number of elements; primitives without boxingLength is fixed when created; few built-in helpers
ArrayListReading by index, adding at the end, general-purpose listsInserting or removing near the front shifts every later element
LinkedListCode that adds and removes at both ends and also wants a ListOne node object per element; get(i) walks the chain, so index loops are slow
ArrayDequeQueues and stacks: fast add and remove at both endsNo index access and no null elements

What Is Fast and What Is Slow

Because the elements live in one array, some operations are instant and others must move or scan many elements:

OperationCostWhy
get(i), set(i, e), size()Constant timeDirect array access
add(e) at the endConstant on averageOccasionally the array is copied into a bigger one
add(i, e), remove(i)Grows with the elements after iLater elements shift right or left
contains(o), indexOf(o)Grows with the sizeElements are checked one by one with equals()

One trap deserves its own warning: with a List<Integer>, list.remove(1) calls remove(int index) and removes the element at index 1. Write list.remove(Integer.valueOf(1)) to remove the value 1. The remove() guide shows both.

Java 21 Methods and Their Classic Equivalents

Java 21 added the SequencedCollection interface, which gives List six methods for working at its ends. They do not compile on Java 8, 11, or 17; each has an older equivalent:

Java 21+Any Java versionOn an empty list
addFirst(e)add(0, e)Works
addLast(e)add(e)Works
getFirst()get(0)NoSuchElementException
getLast()get(size() - 1)NoSuchElementException
removeFirst()remove(0)NoSuchElementException
removeLast()remove(size() - 1)NoSuchElementException

Java Examples

Example 1 — Create, Add, Read, and Loop

A short reading list: append and insert titles, read one by index, replace one, remove one, and loop over the rest.

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

public class ArrayListBasics {
    public static void main(String[] args) {
        List<String> books = new ArrayList<>();
        books.add("Dune");
        books.add("Emma");
        books.add(1, "Ulysses");

        System.out.println(books + " size=" + books.size());
        System.out.println("index 2: " + books.get(2));

        books.set(0, "Dune Messiah");
        books.remove("Emma");
        for (String b : books) {
            System.out.println("- " + b);
        }
    }
}

How It Works

  1. Program to the interface. The variable has type List<String> while the object is an ArrayList, so the code only depends on list operations and the class could be swapped later.
  2. Append, then squeeze in. Two add calls append Dune and Emma; add(1, "Ulysses") inserts a title between them and pushes Emma to index 2.
  3. Read, replace, remove. get(2) reads Emma, set(0, ...) overwrites the first title, and remove("Emma") deletes a title by value.
  4. Loop in index order. The enhanced for loop prints the two titles that remain, first to last.

Example 2 — Store Numbers: Autoboxing, Sorting, and Filtering

A list of test scores: sort it, find a score, drop the failing ones, remove one by value, and add up the rest.

Java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ArrayListNumbers {
    public static void main(String[] args) {
        List<Integer> scores = new ArrayList<>(Arrays.asList(70, 95, 40, 88));

        scores.sort(null);
        System.out.println("sorted: " + scores);
        System.out.println("index of 88: " + scores.indexOf(88));

        scores.removeIf(s -> s < 50);
        scores.remove(Integer.valueOf(95));
        int total = 0;
        for (int s : scores) {
            total += s;
        }
        System.out.println(scores + " total=" + total);
    }
}

How It Works

  1. Wrapper type. Generics only work with objects, so the list is List<Integer>; the plain int literals are boxed into Integer objects automatically.
  2. Sort, then search. sort(null) orders the scores from low to high, after which indexOf(88) finds 88 at index 2.
  3. Two kinds of removal. removeIf drops the failing 40, and Integer.valueOf(95) makes Java pick remove(Object), so 95 is removed as a value rather than treated as an index.
  4. Unboxing in the loop. for (int s : scores) turns each Integer back into an int, and 70 + 88 gives 158.

Example 3 — Fixed Array vs Growable ArrayList

Start with a two-slot array, copy it into an ArrayList that can grow, then convert back to an array.

Java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ArrayVsArrayList {
    public static void main(String[] args) {
        String[] arr = new String[2];
        arr[0] = "x";
        arr[1] = "y";
        System.out.println("array length " + arr.length + ": " + Arrays.toString(arr));

        List<String> list = new ArrayList<>(Arrays.asList(arr));
        list.add("z");
        list.add(0, "w");
        System.out.println("list size " + list.size() + ": " + list);

        String[] back = list.toArray(new String[0]);
        System.out.println("back to array: " + back.length + " elements");
    }
}

How It Works

  1. Fixed length. The array was created with exactly two slots; storing a third string would mean building a whole new array by hand.
  2. Array into a list. new ArrayList<>(Arrays.asList(arr)) copies both strings into a list that is free to grow.
  3. Grows on demand. add("z") appends and add(0, "w") inserts at the front, so the size goes from 2 to 4 with no extra work.
  4. Back to an array. toArray(new String[0]) produces a String[] of length 4 for code that needs a plain array.

Next: Java ArrayList Methods by Group

Full list with short descriptions: Java ArrayList Methods index (/java/array-list/method).

Frequently Asked Questions

ArrayList is a class in java.util that stores elements in order inside a resizable array. You can add, read, replace, and remove elements by index (starting at 0), and the list grows automatically. It implements the List interface.
An array has a fixed length set when it is created and can hold primitives such as int. An ArrayList grows and shrinks as you add and remove elements, has many helper methods, and holds only objects, so numbers are stored as Integer, Double, and so on.
Not directly. Use ArrayList<Integer>; Java converts between int and Integer automatically (autoboxing). Watch out for list.remove(1), which removes index 1, not the value 1.
No. Use it from one thread, or protect it yourself. Collections.synchronizedList(...) wraps it with locking, and CopyOnWriteArrayList in java.util.concurrent suits lists that are read far more often than they are changed.
ArrayList is the usual default: reading by index is fast and it uses less memory per element. LinkedList can add and remove at its ends without shifting, but for queues and stacks ArrayDeque is usually the better choice.

Browse every ArrayList method

Open the methods index for categorized guides with examples and FAQs.

ArrayList Methods Index →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

9 people found this page helpful