Arrays.asList()
Returns a fixed-size list backed by an array.
Available since: Java 1.2
Syntax
static <T> List<T> asList(T... a)Parameters
| Parameter | Type | Description |
|---|---|---|
| a | T... | An array of objects or comma-separated values. |
Return value
List<T>A List backed by the array.
Examples
A list from values; elements can change, the size cannot:
void main() {
List<String> list = Arrays.asList("a", "b", "c");
list.set(0, "z");
IO.println(list);
try {
list.add("d");
} catch (UnsupportedOperationException e) {
IO.println("cannot add");
}
}Output:
[z, b, c]
cannot addA regular mutable list from an array — wrap it in an ArrayList:
void main() {
String[] array = {"Anna", "Oleg"};
List<String> names = new ArrayList<>(Arrays.asList(array));
names.add("Maria");
IO.println(names);
}Output:
[Anna, Oleg, Maria]Notes
The list and the array are linked: set() changes the array, and changes to the array show up in the list. For an immutable list List.of(...) is handier. With a primitive array the method behaves unexpectedly: Arrays.asList(new int[] {1, 2}) returns a list of one element — the array itself; for int[] use Arrays.stream(a).boxed().toList().
See also
- Arrays.stream() — Creates a stream from an array — for sums, filters and transformations.
- Arrays.toString() — Returns the contents of an array as a string like [1, 2, 3].
Related recipes
In the tutorial
- The Arrays class — Utilities of java.util.Arrays: toString, sort, fill, copyOf, copyOfRange, equals and binarySearch.