Arrays AsList Fixed Size View

Arrays.asList gives a fixed-size view: set writes through to the array, add and remove throw; List.of forbids even set; copy into ArrayList to mutate.

JavaData Integrity

Code

snippet
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class FixedSizeTrap {

    public static void main(String[] args) {
        // Arrays.asList 返回定长视图:set 直接写穿底层数组,add/remove 抛异常
        String[] backing = {"a", "b", "c"};
        List<String> view = Arrays.asList(backing);
        view.set(0, "A");
        System.out.println("backing[0] = " + backing[0]);

        try {
            view.add("d");
        } catch (UnsupportedOperationException e) {
            System.out.println("add rejected: fixed-size list");
        }

        // List.of 完全不可变:连 set 都不行
        List<String> frozen = List.of("a", "b", "c");
        try {
            frozen.set(0, "x");
        } catch (UnsupportedOperationException e) {
            System.out.println("set rejected: immutable list");
        }

        // 要可变副本:包一层 ArrayList,两个世界都不沾
        List<String> mutable = new ArrayList<>(Arrays.asList("a", "b", "c"));
        mutable.add("d");
        System.out.println(mutable);
    }
}

Inside the snippet

Count the class FixedSizeTrap and the function main as the entire surface area of Arrays AsList Fixed Size View.

Putting it to use

The primary signature is public static void main(String[] args)

Running the file prints labeled results such as backing[0] =, add rejected: fixed-size list, set rejected: immutable list — each operation’s effect is visible in the output.

Core lines

List<String> mutable = new ArrayList<>(Arrays.asList("a", "b", "c"));
List<String> frozen = List.of("a", "b", "c");
List<String> view = Arrays.asList(backing);

Interactive Tools for This Topic

FAQ

What does Arrays AsList Fixed Size View print when run?
The script runs standalone; its 3 labeled outputs include `backing[0] =`, `add rejected: fixed-size list`, `set rejected: immutable list`.