Java Reference ยท Collections
Java Arrays.asList() method
Reference for Java Arrays.asList(): a fixed-size list backed by an array, write-through behavior, the primitive-array trap, and when to use List.of.
Arrays.asList() wraps an array (or a list of arguments) in a List. The list is a view of the array: reading and set() work, and writes go through to the array in both directions. But the size is fixed, so add() and remove() throw UnsupportedOperationException.
It is handy for quick lists, for passing an array to an API that wants a collection, and for sorting or shuffling an object array through list algorithms.
List<String> names = Arrays.asList("Ann", "Bob", "Cy");
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Syntax
@SafeVarargs public static <T> List<T> asList(T... a)
| Name | Description |
|---|---|
a |
The array backing the list, or the individual elements as varargs. |
Returns: a fixed-size List<T> that writes through to the array.
Throws: NullPointerException if the array itself is null. Later calls to add, remove, clear and similar throw UnsupportedOperationException.
Usage notes
- Fixed size, mutable elements:
set,sort,replaceAll,Collections.swapandCollections.shufflework. Anything that changes the length does not. - Shares storage: changes to the array show up in the list and vice versa. If you want independence, copy:
new ArrayList<>(Arrays.asList(arr)). - Primitive arrays do not convert:
Arrays.asList(int[])givesList<int[]>with one element. UseInteger[]or a stream withboxed(). nullelements are allowed, unlikeList.of.List.of(...)is an alternative (Java 9+): truly immutable, rejectsnull, and does not share storage with an array.List.of(array)with aString[]also works through varargs, copying the elements.- Equality and hash code follow the
Listcontract, soArrays.asList(1, 2).equals(List.of(1, 2))istrue. containsandindexOfareO(n);getandsetareO(1).- Array covariance:
Arrays.asList(new Integer[]{1})is aList<Integer>, but aString[]stored in anObject[]variable can fail at run time when yousetthe wrong type (ArrayStoreException).
Related
- Arrays, List.of(), ArrayList, Collections
- Lessons: The Arrays class, ArrayList