Library contents

Java List.copyOf

Make an unmodifiable list containing the current elements of a collection in encounter order.

A simple example

List.copyOf

  1. Start with Original list A, B
  2. Do this Copy it, then append C to the original
  3. Result Copy still has A, B
The list of elements in the earlier snapshot is unaffected by the later append.

Syntax

Java syntax
List.copyOf(draft)
Run these examples in Java

Save one example at a time as Main.java. Use JDK 21.

java Main.java

Freeze 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.

Result2
Main.java
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());
    }
}
Output
2

The new guest changes the draft size to three. The printed snapshot still has two names.

Advertisements

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.

From the programvar printed = List.of("Rice", "Soup")
Result2 printed, 3 draft
Main.java
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");
    }
}
Output
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?

GivenSnapshot Pia, Kai · later add Mira
Worked resultPia · Kai

What to watch for

The copy is shallow and rejects null elements. Later changes inside a shared mutable element may still be visible.

Documentation for List.copyOf