Java Tutorial · Collections · Lesson 25 of 37
Java ArrayList
A resizable list: add, get, set, remove, loop and sort.
ArrayList
ArrayList is a list that grows as you add items. Declare variables with the List interface and choose the implementation on the right:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> todo = new ArrayList<>();
todo.add("Write code");
todo.add("Test");
todo.add(0, "Plan"); // insert at index 0
todo.set(2, "Write tests");
System.out.println(todo + " size=" + todo.size());
System.out.println(todo.get(1) + " " + todo.contains("Test") + " " + todo.indexOf("Write tests"));
todo.remove("Plan");
for (String item : todo) System.out.println("- " + item);
List<Integer> nums = new ArrayList<>(List.of(5, 3, 9, 1));
Collections.sort(nums);
System.out.println(nums);
nums.removeIf(n -> n > 4);
System.out.println(nums);
}
}
Output
[Plan, Write code, Write tests] size=3 Write code false 2 - Write code - Write tests [1, 3, 5, 9] [1, 3]
Run this on your computer — see “Get Started” for setup.
Collections hold objects, so use wrapper types: List<Integer>, not List<int>.
Immutable lists
List.of(...) creates an unmodifiable list — adding to it throws UnsupportedOperationException. Use it for fixed data:
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> days = List.of("Mon", "Tue", "Wed");
System.out.println(days);
try {
days.add("Thu");
} catch (UnsupportedOperationException e) {
System.out.println("List.of() lists are immutable");
}
List<String> copy = new ArrayList<>(days);
copy.add("Thu");
System.out.println(copy);
}
}
Output
[Mon, Tue, Wed] List.of() lists are immutable [Mon, Tue, Wed, Thu]
Run this on your computer — see “Get Started” for setup.
LinkedList also implements List, but ArrayList is faster for almost every real use case.
Test yourself
Why can't you write List<int>?
int is too smallGenerics only work with objects, so use List<Integer>Lists can't hold numbersYou can — it's allowed
Show answer
Answer: Generics only work with objects, so use List<Integer>