CKTIS / Java
Arrays.asList — a fixed-size list backed by an array
Arrays.asList creates a fixed-size list view of an array. Elements can be replaced, but the size cannot change; the list and array share their data.
Version: Java SE 21; repository runtime, production runtime not attested
Syntax
public static <T> List<T> asList(T... a)Arrays.asList from java.util.Arrays returns a List<T> backed by an array, not an independent copy. It accepts a reference array or varargs arguments, such as Arrays.asList("A", "B").
Fixed-size does not mean unmodifiable: set replaces an element. Changes are visible in both directions. Adding an element with add or removing an existing element throws UnsupportedOperationException.
Pitfall: Arrays.asList(new int[]{1, 2}) produces a List<int[]> containing one element, not a List<Integer>. A primitive array is not automatically converted into an array of wrapper objects.
The array may contain null, but passing null as the array itself throws NullPointerException. If the array's actual component type is narrower than T, an incompatible replacement can throw ArrayStoreException.
Examples
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args) {
String[] array = {"A", "B"};
List<String> list = Arrays.asList(array);
list.set(0, "X");
array[1] = "Y";
System.out.println(list);
System.out.println(Arrays.toString(array));
try {
list.add("Z");
} catch (UnsupportedOperationException e) {
System.out.println("UnsupportedOperationException");
}
int[] numbers = {1, 2};
System.out.println(Arrays.asList(numbers).size());
}
}Result
[X, Y] [X, Y] UnsupportedOperationException 1
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.