ArrayList
A resizable list backed by an array — the most common `List` implementation.
Available since: Java 1.2
Syntax
public class ArrayList<E> implements List<E>, RandomAccessExamples
An empty list that elements are added to:
void main() {
List<String> tasks = new ArrayList<>();
tasks.add("write code");
tasks.add("run tests");
tasks.add("commit");
IO.println(tasks);
IO.println(tasks.get(1));
}Output:
[write code, run tests, commit]
run testsA list with initial elements taken from another collection:
void main() {
var prices = new ArrayList<>(List.of(10, 25, 5));
prices.remove(Integer.valueOf(25));
prices.add(40);
IO.println(prices);
}Output:
[10, 5, 40]Notes
The variable is usually declared with the interface type: List<String> list = new ArrayList<>(). Access by index is fast, while inserting or removing at the start or in the middle shifts the remaining elements. It stores objects only: numbers use the wrappers Integer, Double. The class is not thread-safe.
See also
- List.of() — Creates an unmodifiable list from the listed elements.
- List.add() — Adds an element to the end of a list or at a given position.
- List.get() — Returns the list element at an index.
- LinkedList — A doubly linked list that implements both `List` and `Deque`.
- List.size() — Returns the number of elements in a list.
In the tutorial
- Lists: List and ArrayList — Lists in Java: ArrayList, adding, reading and removing elements, unmodifiable List.of lists and lists of numbers.