List.copyOf()
Creates an unmodifiable list copy of a collection.
Available since: Java 10
Syntax
static <E> List<E> copyOf(Collection<? extends E> coll)Parameters
| Parameter | Type | Description |
|---|---|---|
| coll | Collection<? extends E> | The collection whose elements are copied. |
Return value
List<E>An unmodifiable list holding the elements of the collection.
Examples
The copy does not change together with the original:
void main() {
List<String> cart = new ArrayList<>(List.of("tea", "milk"));
List<String> snapshot = List.copyOf(cart);
cart.add("bread");
IO.println(cart);
IO.println(snapshot);
}Output:
[tea, milk, bread]
[tea, milk]Notes
Handy when a method returns a class's internal list: the caller gets a copy and cannot change it. If the given collection is already unmodifiable (created with List.of()), no copy may be made. null elements are forbidden.
See also
- List.of() — Creates an unmodifiable list from the listed elements.
- Collections.unmodifiableList() — Returns a view of a list that cannot be modified.
- 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.