Java List.copyOf
Make an unmodifiable list containing the current elements of a collection in encounter order.
A simple example
List.copyOf
- Start with Original list A, B
- Do this Copy it, then append C to the original
- Result Copy still has A, B
Syntax
List.copyOf(draft)
Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaFreeze the guest list used to print badges
A school prints badges from a draft guest list. A late guest joins after printing starts, so the team keeps a snapshot that records exactly how many badges belonged to the original run.
import java.util.ArrayList;
import java.util.List;
class Main {
public static void main(String[] args) throws Exception {
var draft = new ArrayList<>(List.of("Mira", "Sam"));
var printed = List.copyOf(draft);
draft.add("Nia");
System.out.println(printed.size());
}
}
2
The new guest changes the draft size to three. The printed snapshot still has two names.
Give a volunteer an editable copy
A volunteer starts with the published list of lunch choices. She needs to propose another option without changing the two choices already printed on the menu.
import java.util.ArrayList;
import java.util.List;
class Main {
public static void main(String[] args) throws Exception {
var printed = List.of("Rice", "Soup");
var draft = new ArrayList<>(printed);
draft.add("Fruit");
System.out.println(printed.size() + " printed, " + draft.size() + " draft");
}
}
2 printed, 3 draft
The ArrayList constructor produces a mutable list that can grow independently.
Freeze the morning guest list
The school prints the first two names before a late guest registers. After saving a snapshot, add the late entry only to the working list. Which names remain visible on the snapshot?
What to watch for
The copy is shallow and rejects null elements. Later changes inside a shared mutable element may still be visible.