Java SE API
List.copyOf(Collection)
Returns an unmodifiable list of the collection elements in iteration order. Rejects null collection or elements. The snapshot does not clone mutable elements. Since Java 10.
Formal Syntax & Structure
java syntaxjava
static <E> List<E> copyOf(Collection<? extends E> coll)Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| coll | Collection<? extends E> | Non-null collection of non-null elements. |
Return Value
List<E>
Unmodifiable snapshot of element references.
Working Example
Example Snippetjava
import java.util.ArrayList;import java.util.List;public class Main { record ReadingList(List<String> titles) { ReadingList { titles = List.copyOf(titles); } } public static void main(String[] args) { List<String> source = new ArrayList<>(); source.add("Maps"); ReadingList list = new ReadingList(source); source.add("Loops"); System.out.println(list.titles()); System.out.println(list.equals(new ReadingList(List.of("Maps")))); try { list.titles().add("Arrays"); } catch (UnsupportedOperationException e) { System.out.println("Read only"); } }}