CKTIS / Java
List.addAll — append or insert elements
Use `List.addAll` to append the elements of a collection or insert them at a chosen index. The `boolean` result tells you whether the destination list changed.
Version: Java SE 21
Syntax
boolean addAll(Collection<? extends E> c)
boolean addAll(int index, Collection<? extends E> c)In Java SE 21, the java.util.List<E> interface has two List.addAll overloads. List.addAll(Collection) appends elements to the destination list in the order produced by the source collection's iterator. If the source is another list, its elements follow the destination's existing elements in their original order. The method does not sort or deduplicate. Collection<? extends E> means the source need not be a list, and its declared element type can be E or a subtype of E.
List.addAll(int, Collection) inserts the elements starting at a zero-based index, using the same source order. Existing elements at and after that position shift right. Valid indices range from 0 through size(), inclusive; size() appends at the end. An index outside that range can cause IndexOutOfBoundsException.
Both overloads modify the list they are called on. They return true if the list changed and false if it did not. For example, adding an empty collection to an ArrayList returns false. The result is not a new list. To keep the first list unchanged, create new ArrayList<>(first) and add the second list's elements to that copy.
Adding is optional: List.of(...) works as a source, but as a destination it throws UnsupportedOperationException. A destination that does not support the operation can throw this exception before checking the arguments. A null argument can cause NullPointerException, as can a null element if the destination disallows it. Restrictions on an element's class or other properties can cause ClassCastException or IllegalArgumentException, respectively. Do not modify the source during the call: the behavior is undefined if you do, including when a nonempty list is its own source.
Examples
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> first = List.of("A", "B");
List<String> second = List.of("B", "C");
List<String> result = new ArrayList<>(first);
System.out.println(result.addAll(second));
System.out.println(result);
result.addAll(1, List.of("X", "Y"));
System.out.println(result);
System.out.println(result.addAll(List.of()));
}
}Result
true [A, B, B, C] [A, X, Y, B, B, C] false
The program makes a mutable copy of `first`. Appending `second` returns `true` and keeps both occurrences of `B`; inserting at index `1` puts `X` and `Y` after `A`; adding an empty collection returns `false`.
Related lessons
- Java · Lesson 14 · Advanced · Version: 2
- Java · Lesson 54 · Basic · Version: 2