Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

List.add()

Adds an element to the end of a list or at a given position.

Available since: Java 1.2

Syntax

boolean add(E e)
void add(int index, E element)

Parameters

ParameterTypeDescription
indexintOptional insert position; elements from this position shift to the right.
eEThe element to add.

Return value

booleanThe version without an index returns `true`; the version with an index returns nothing.

Examples

Adding to the end:

void main() {
    List<String> fruits = new ArrayList<>();
    fruits.add("apple");
    fruits.add("pear");
    IO.println(fruits);
}

Output:

[apple, pear]

Inserting at an index:

void main() {
    List<String> fruits = new ArrayList<>(List.of("apple", "pear"));
    fruits.add(0, "kiwi");
    fruits.add(2, "plum");
    IO.println(fruits);
}

Output:

[kiwi, apple, plum, pear]

Notes

The index may be from 0 to size() inclusive: add(size(), x) is the same as add(x). A larger index throws IndexOutOfBoundsException. Unmodifiable lists (List.of()) throw UnsupportedOperationException.

See also

  • List.addAll() — Adds all elements of another collection to a list.
  • List.set() — Replaces the list element at an index.
  • List.remove() — Removes a list element by index or by value.
  • ArrayList — A resizable list backed by an array — the most common `List` implementation.

Related recipes

In the tutorial

  • Lists: List and ArrayList — Lists in Java: ArrayList, adding, reading and removing elements, unmodifiable List.of lists and lists of numbers.

Thanks for reading!

Donate to the site — we work hard for you.