CKTIS / Java
List.copyOf: an unmodifiable, shallow list copy
`List.copyOf` returns an unmodifiable snapshot in the source collection’s iteration order. It shares element objects and rejects `null`.
Version: Java SE 21
Syntax
static <E> List<E> copyOf(Collection<? extends E> coll)
List<E> snapshot = List.copyOf(coll);List.copyOf is a static method on java.util.List, available since Java 10. It accepts a Collection<? extends E>, not just a list: elements can be of type E or a subtype. The result is a List<E> in the source collection’s iteration order, with duplicates preserved.
Adding, removing, or replacing elements in the result throws UnsupportedOperationException. Later changes to the source collection, including replacing an element, do not change the snapshot. By contrast, Collections.unmodifiableList returns an unmodifiable view that reflects changes to the backing list.
The copy is shallow: the snapshot holds references to the same element objects. Changing a shared StringBuilder is therefore visible through the snapshot. String objects are immutable, so sharing them does not pose that risk. If you need independent state for mutable elements, copy those elements too.
If the collection itself or any element is null, the call throws NullPointerException when creating the snapshot. The method may reuse a suitable unmodifiable list, so do not assume that the result is always a new instance.
Examples
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> source = new ArrayList<>(List.of("red", "blue"));
List<String> snapshot = List.copyOf(source);
source.set(0, "green");
System.out.println("source: " + source);
System.out.println("snapshot: " + snapshot);
try {
snapshot.add("yellow");
} catch (UnsupportedOperationException e) {
System.out.println("UnsupportedOperationException");
}
StringBuilder shared = new StringBuilder("A");
List<StringBuilder> mutableSnapshot = List.copyOf(List.of(shared));
shared.append("B");
System.out.println("shared element: " + mutableSnapshot.get(0));
source.add(null);
try {
List.copyOf(source);
} catch (NullPointerException e) {
System.out.println("NullPointerException");
}
}
}Result
source: [green, blue] snapshot: [red, blue] UnsupportedOperationException shared element: AB NullPointerException
Replacing `red` with `green` changes only the source, and adding to the snapshot fails. The shared `StringBuilder` changes to `AB`. After `null` is added to the source, the next snapshot attempt throws `NullPointerException`.
Related lessons
- Java · Lesson 1 · Advanced · Version: 2
- Java · Lesson 44 · Intermediate · Version: 2