Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

List.add(E) — append an element to a list

`List.add(E)` appends one element to the existing list and returns `true` if the call completes normally. Not every list supports adding elements.

Version: Java SE 21

Syntax

boolean add(E e)

boolean added = items.add(element);

List.add(E) is the one-argument method on java.util.List<E>. E is the element type, such as Customer in a repository backed by List<Customer>. The method modifies the existing list: the new element goes at the end, and earlier elements keep their order. A normal return is true, not an index or a new list.

The list stores the reference you pass, not a copy of the object. An ArrayList can store the same reference more than once; changes to the shared object are visible through every position that refers to it. Lists typically allow duplicates, so repeated add calls work well for recording events or recipients in the order they are added.

Appending is optional: a list from List.of(...) is unmodifiable and throws UnsupportedOperationException. A list that supports appending can still reject an element: NullPointerException for disallowed null, ClassCastException for an unacceptable element class, or IllegalArgumentException for another unacceptable property of the element. ArrayList permits null.

The overload add(int index, E element) returns void and inserts at an index from 0 through size(), shifting any elements at or after that position. When undoing a removal, use the saved index if you need to restore the original position; add(element) only appends. Since Java 21, addLast(E) also appends, but returns void.

Examples

import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<StringBuilder> items = new ArrayList<>();
        StringBuilder first = new StringBuilder("Ada");

        boolean added = items.add(first);
        items.add(new StringBuilder("Lin"));
        items.add(first);

        System.out.println(added);
        System.out.println(items);
        System.out.println(items.get(0) == items.get(2));
        first.append("!");
        System.out.println(items);
    }
}

Result

true
[Ada, Lin, Ada]
true
[Ada!, Lin, Ada!]

The first `true` is the result of `add`; the second is the result of comparing references with `==`. After `first` is changed, both positions show `Ada!` because they refer to the same object.

Related lessons

  • Java · Lesson 21 · Intermediate · Version: 2
  • Java · Lesson 22 · Intermediate · Version: 2
  • Java · Lesson 26 · Intermediate · Version: 2
  • Java · Lesson 27 · Intermediate · Version: 2
  • Java · Lesson 32 · Intermediate · Version: 2

Sources