Java ArrayList

Use ArrayList for lists that grow and shrink: add, get, set, remove, search, sort and loop through items.

Lesson 46 of 127Intermediate17 min read

Arrays are fast, but their size is fixed. Real programs are full of lists that change: items are added to a shopping basket, tasks are ticked off a to-do list, players join and leave a game. For lists like these, Java gives you ArrayList, a resizable list from the java.util package.

An ArrayList grows automatically as you add items and shrinks when you remove them. It keeps items in order, allows duplicates and lets you reach any item by its index, just like an array. On top of that it has convenient methods for searching, inserting and removing, so you rarely have to shuffle elements around yourself.

ArrayList is part of Java's Collections Framework, a family of ready-made data structures. In this lesson you'll create typed lists with generics, add and remove items, search and sort them, and learn the small details, such as wrapper types and removing during a loop, that trip up beginners.

Creating an ArrayList

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

List<String> names = new ArrayList<>();
names.add("Ana");
names.add("Ben");
  • The type in angle brackets, <String>, is a generic type: it says what the list holds, and the compiler stops you adding anything else.
  • <> on the right is the "diamond": Java fills in the type for you.
  • It's good practice to declare the variable as the List interface and create an ArrayList. That way you could switch to another kind of list later without changing the rest of your code.

You can also create a list with starting values: new ArrayList<>(List.of("Ana", "Ben")).

Core methods

MethodWhat it does
list.add(x)Add to the end
list.add(i, x)Insert at position i, shifting later items
list.get(i)Read the item at position i
list.set(i, x)Replace the item at position i
list.remove(i) / list.remove(x)Remove by position / by value
list.size()Number of items
list.contains(x)true if the item is in the list
list.indexOf(x)Position of the item, or -1
list.clear() / list.isEmpty()Remove everything / check for none

Note size() with brackets, unlike an array's length. Indexes start at 0, and an invalid index throws IndexOutOfBoundsException.

Wrapper classes for numbers

Collections can only hold objects, not primitive types like int or double. Each primitive has a wrapper class: Integer, Double, Boolean, Character and so on. Write List<Integer>, not List<int>:

Java
List<Integer> scores = new ArrayList<>();
scores.add(72);            // int is "autoboxed" into an Integer
int first = scores.get(0); // and "unboxed" back into an int

Java converts between the two automatically, which is called autoboxing. One catch: with a List<Integer>, remove(1) removes the element at index 1, not the value 1. Use remove(Integer.valueOf(1)) to remove by value.

Sorting and looping

Java
Collections.sort(names);                        // A to Z
names.sort(Comparator.reverseOrder());          // Z to A
products.sort(Comparator.comparing(Product::getPrice));

Loop through a list with the enhanced for loop, for (String n : names), or with forEach: names.forEach(System.out::println). To remove items while looping, don't call list.remove() inside an enhanced for loop; it throws a ConcurrentModificationException. Use list.removeIf(n -> n.startsWith("A")) instead. You'll learn more about the arrow syntax in the lambdas and streams lesson.

Java ArrayList Syntax

ArrayList syntax

import java.util.*;

List<Type> list = new ArrayList<>();
list.add(value);
list.get(index);
list.set(index, value);
list.remove(index);
list.size();
Collections.sort(list);
list.removeIf(x -> condition);

Java ArrayList Summary

  • List<Type> list = new ArrayList<>(); creates a resizable, ordered list.
  • add, get, set, remove, size, contains and indexOf cover most needs.
  • Use wrapper types such as Integer and Double in collections.
  • Sort with Collections.sort or list.sort(Comparator...).
  • Use removeIf rather than removing inside an enhanced for loop.

Java ArrayList Examples

Each example shows the code, the output it produces and what each part does.

Example 1

A to-do list

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

public class Main {
    public static void main(String[] args) {
        List<String> todo = new ArrayList<>();
        todo.add("Buy milk");
        todo.add("Walk the dog");
        todo.add("Finish homework");
        todo.add(1, "Call Grandma");

        System.out.println(todo);
        todo.remove("Walk the dog");
        todo.set(0, "Buy oat milk");

        for (int i = 0; i < todo.size(); i++) {
            System.out.println((i + 1) + ". " + todo.get(i));
        }
        System.out.println("Homework on the list? " + todo.contains("Finish homework"));
    }
}
Output
[Buy milk, Call Grandma, Walk the dog, Finish homework]
1. Buy oat milk
2. Call Grandma
3. Finish homework
Homework on the list? true
Line-by-line explanation
  1. Line 10add with an index inserts at that position and shifts the rest along.
  2. Line 12Lists print in a readable format.
  3. Line 13Remove by value.
  4. Line 14Replace the first item.
  5. Lines 16 to 18size() and get() work like an array's length and [i].
Example 2

Numbers in a list

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

public class Main {
    public static void main(String[] args) {
        List<Integer> scores = new ArrayList<>(List.of(72, 95, 61, 88, 61));

        scores.remove(Integer.valueOf(61));
        Collections.sort(scores);
        int max = Collections.max(scores);
        int total = 0;
        for (int s : scores) total += s;

        System.out.println(scores + " max " + max + " total " + total);
    }
}
Output
[61, 72, 88, 95] max 95 total 316
Line-by-line explanation
  1. Line 7List.of gives starting values; new ArrayList makes the list changeable.
  2. Line 9Integer.valueOf(61) removes the first 61 by value, not the item at index 61.
  3. Lines 10 to 11Collections has helpers for sorting and finding the maximum.
  4. Line 13Each Integer is unboxed into an int automatically.
Example 3

Sorting objects and removing safely

Java
import java.util.*;

public class Main {
    record Product(String name, double price) {}

    public static void main(String[] args) {
        List<Product> products = new ArrayList<>(List.of(
            new Product("Desk lamp", 24.50),
            new Product("Pen", 1.20),
            new Product("Backpack", 34.99),
            new Product("Notebook", 3.50)
        ));

        products.sort(Comparator.comparing(Product::price));
        products.removeIf(p -> p.price() > 30);

        for (Product p : products) {
            System.out.printf("%-10s %6.2f%n", p.name(), p.price());
        }
    }
}
Output
Pen          1.20
Notebook     3.50
Desk lamp   24.50
Line-by-line explanation
  1. Line 4A record is a short way to define a simple data class (Java 16+).
  2. Line 14Comparator.comparing sorts the products by price, cheapest first.
  3. Line 15removeIf deletes every product that matches the condition, safely.
  4. Line 18%-10s pads the name to 10 characters so the prices line up.

Common Java ArrayList Mistakes

Using a primitive type in a collection

Don't
List<int> numbers = new ArrayList<>();
Do
List<Integer> numbers = new ArrayList<>();

remove(1) on a list of Integers

Don't
List<Integer> ids = new ArrayList<>(List.of(5, 1, 7));
ids.remove(1);                     // removes the item at index 1: [5, 7]... by accident
Do
ids.remove(Integer.valueOf(1));    // removes the value 1

Removing inside an enhanced for loop

Don't
for (String n : names) {
    if (n.isBlank()) names.remove(n);   // ConcurrentModificationException
}
Do
names.removeIf(String::isBlank);

Java ArrayList in Real Projects

ArrayList in real projects

Java applications are full of lists: the items in a basket, the search results for a query, the messages in a chat, the rows read from a database. Frameworks such as Spring return List objects from database queries, and Android apps hand lists to a RecyclerView to display scrolling content.

Java ArrayList FAQ

What is the difference between an array and an ArrayList?

An array has a fixed size, can hold primitives directly and uses length and square brackets. An ArrayList grows and shrinks automatically, only holds objects such as Integer, and uses methods: add, get, set and size(). Use an ArrayList whenever the number of items changes.

Should I use ArrayList or LinkedList?

Use ArrayList in almost every case. It reads any position instantly and is very fast to loop through because its items sit together in memory. LinkedList is only faster for frequent inserts and removals at the start of a list, and ArrayDeque usually does that job better.

How do I remove duplicates from an ArrayList?

Copy it through a LinkedHashSet, which drops duplicates and keeps the original order: new ArrayList<>(new LinkedHashSet<>(list)). A list of b, a, b, c, a becomes b, a, c. Use a TreeSet instead if you want the result sorted.

How do I convert an ArrayList to an array?

Call list.toArray(new String[0]), passing an empty array of the element type. Java creates an array of the right size and copies the items into it. For a List<Integer> that should become an int[], use list.stream().mapToInt(Integer::intValue).toArray().

Is ArrayList thread-safe?

No. If several threads change the same ArrayList at once, it can lose items or throw exceptions. Use Collections.synchronizedList(...), a CopyOnWriteArrayList for lists that are read often and changed rarely, or keep each list inside one thread.

Java ArrayList Exercises

Answer each one and check it instantly. If you get stuck, open the hint before the answer.

Fill in the blankseasy

Complete the code so the list holds Strings and "Tea" is added.

List<> drinks = new ArrayList<>();
drinks.("Tea");
Predict the outputeasy

What does this print?

List<String> l = new ArrayList<>(List.of("a", "b", "c"));
l.remove(0);
System.out.println(l.size() + " " + l.get(0));
Predict the outputmedium

What does this print?

List<Integer> n = new ArrayList<>(List.of(10, 20, 30));
n.set(1, 25);
n.add(0, 5);
System.out.println(n);
Multiple choicemedium

How do you get the number of items in an ArrayList called list?

Multiple choicehard

Which is the safe way to remove every empty string from a list while looping?

Java ArrayList Quiz

5 questions to check what you learned.

  1. What's the main advantage of ArrayList over an array?

    • It's always faster
    • It can hold primitive ints directly
    • It can grow and shrink as items are added and removed
    • It doesn't need indexes
  2. What is Integer?

    • A keyword for whole numbers
    • The wrapper class for int, used in collections
    • A kind of ArrayList
    • A method that converts strings
  3. Why write List<String> list = new ArrayList<>(); instead of ArrayList<String> list?

    • It's required
    • It makes the list faster
    • It allows duplicate items
    • Coding to the List interface makes it easy to change the implementation later
  4. What does list.indexOf("x") return if "x" isn't in the list?

    • -1
    • 0
    • null
    • An exception
  5. What does Comparator.comparing(Product::price) do?

    • Sorts products alphabetically
    • Removes products with no price
    • Creates a rule that compares products by their price
    • Finds the cheapest product