TExcelTAD
Home › Java › Java ArrayList

Java ArrayList

Arrays have a fixed size. Most of the time, though, you don't know in advance how many items you'll have — orders in a cart, lines in a file, players in a game. ArrayList from java.util is a resizable array: it grows and shrinks automatically as you add and remove elements. It is the most used collection in Java.

Creating a list and adding elements

The type of the elements goes in angle brackets — this is called a generic type. ArrayList holds objects, so for numbers you use the wrapper classes Integer, Double, etc. instead of int, double.

java · try it yourself
import java.util.ArrayList;

class Main {
    public static void main(String[] args) {
        ArrayList<String> tasks = new ArrayList<>();
        tasks.add("Write report");
        tasks.add("Email Sam");
        tasks.add("Book flights");
        tasks.add(1, "Coffee");          // insert at index 1

        System.out.println(tasks);
        System.out.println("Size: " + tasks.size());
        System.out.println("First: " + tasks.get(0));
    }
}
[Write report, Coffee, Email Sam, Book flights]
Size: 4
First: Write report

The <> on the right ("diamond") lets the compiler infer the element type from the left side.

Changing and removing elements

java · try it yourself
import java.util.ArrayList;

class Main {
    public static void main(String[] args) {
        ArrayList<String> colors = new ArrayList<>();
        colors.add("red");
        colors.add("green");
        colors.add("blue");
        colors.add("green");

        colors.set(0, "crimson");            // replace by index
        colors.remove("green");              // removes the FIRST "green"
        System.out.println(colors);
        colors.remove(0);                    // remove by index
        System.out.println(colors);
        System.out.println(colors.contains("blue") + " " + colors.indexOf("green"));
        colors.clear();
        System.out.println(colors.isEmpty());
    }
}
[crimson, blue, green]
[blue, green]
true 1
true

Common methods

Method Description
add(e) / add(i, e) append / insert at index
get(i) element at index
set(i, e) replace element at index
remove(i) / remove(obj) remove by index / first equal object
size() number of elements
contains(obj) / indexOf(obj) search (uses equals)
isEmpty() / clear() test for / remove all elements
addAll(collection) append another collection
removeIf(condition) remove all matching elements

Looping through a list

java · try it yourself
import java.util.ArrayList;
import java.util.List;

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

        int sum = 0;
        for (int s : scores) {               // for-each: auto-unboxing to int
            sum += s;
        }
        System.out.println("Average: " + (double) sum / scores.size());

        for (int i = 0; i < scores.size(); i++) {
            System.out.println("#" + (i + 1) + ": " + scores.get(i));
        }

        scores.forEach(s -> System.out.print(s >= 60 ? "pass " : "fail "));
        System.out.println();
    }
}
Average: 78.25
#1: 72
#2: 95
#3: 58
#4: 88
pass pass fail pass 

Declaring the variable as List<Integer> (the interface) rather than ArrayList<Integer> is common practice — it keeps your code flexible.

The remove(int) trap with Integer lists

For a List<Integer>, remove(1) removes the element at index 1, not the value 1. Wrap the value to remove by value:

java · try it yourself
import java.util.ArrayList;
import java.util.List;

class Main {
    public static void main(String[] args) {
        List<Integer> nums = new ArrayList<>(List.of(5, 9, 7, 1));
        nums.remove(1);                       // index 1 -> removes 9
        System.out.println(nums);
        nums.remove(Integer.valueOf(7));      // value 7
        System.out.println(nums);
        nums.removeIf(n -> n < 3);            // all values below 3
        System.out.println(nums);
    }
}
[5, 7, 1]
[5, 1]
[5]

Sorting and immutable lists

java · try it yourself
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

class Main {
    public static void main(String[] args) {
        List<String> names = new ArrayList<>(List.of("Zoe", "adam", "Mia", "Leo"));
        Collections.sort(names);
        System.out.println(names);                      // uppercase sorts before lowercase
        names.sort(String.CASE_INSENSITIVE_ORDER);
        System.out.println(names);

        List<String> fixed = List.of("a", "b");
        try {
            fixed.add("c");
        } catch (UnsupportedOperationException e) {
            System.out.println("List.of creates an unmodifiable list");
        }
    }
}
[Leo, Mia, Zoe, adam]
[adam, Leo, Mia, Zoe]
List.of creates an unmodifiable list

Note: List.of(...) is great for fixed data. Wrap it in new ArrayList<>(...) when you need to modify the list.

ArrayList vs. array

Array ArrayList
Size fixed grows automatically
Element types primitives or objects objects only (Integer, not int)
Length arr.length list.size()
Access arr[i] list.get(i)
Printing needs Arrays.toString println(list) works

Test yourself

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

  1. list.length
  2. list.length()
  3. list.size()
  4. list.count()

Why can't you write ArrayList<int>?

  1. int is too small
  2. Generics only work with reference types; use Integer
  3. ArrayList only stores Strings
  4. You can, it is valid

For List<Integer> l = new ArrayList<>(List.of(4, 5, 6));, what does l.remove(1) remove?

  1. The value 1
  2. The value 5 (index 1)
  3. The value 4
  4. Nothing