Java 25 (LTS) reference · List and ArrayList Methods
Java List add() Method
Append an element to the end of a list, or insert it at an index, shifting later elements right.
Java 25 (LTS) Since Java 1.0
Syntax
list.add(element) / list.add(index, element)
Parameters
| Parameter | Description |
|---|---|
index optionalint |
Where to insert. |
elementE |
The value to add. |
Return value
true (for add(e)).
Examples
import java.util.*;
public class Main {
public static void main(String[] args) {
List<String> cart = new ArrayList<>();
cart.add("tea");
cart.add("mug");
cart.add(0, "kettle");
System.out.println(cart);
}
}
Output
[kettle, tea, mug]
Run this on your computer — see “Get Started” for setup.
import java.util.*;
public class Main {
public static void main(String[] args) {
List<Integer> nums = new ArrayList<>(List.of(1, 2));
nums.addAll(List.of(3, 4));
System.out.println(nums);
}
}
Output
[1, 2, 3, 4]
Run this on your computer — see “Get Started” for setup.
Version history
| Version | Change |
|---|---|
| Java Java 1.0 | Added |
Related
list.remove()· Remove an element by index or by value. With a List<Integer>, remove(1) removes index 1, not the value 1.list.get()· Return the element at an index (0-based). Throws IndexOutOfBoundsException for an invalid index.- Java ArrayList · tutorial