Skip to content
Tutorials Center
My learning

Topics

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.

Java
List<String> names = Arrays.asList("Ann", "Bob", "Cy");

Try it

Java A write-through view

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.

Java The primitive array trap

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

Java
@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.swap and Collections.shuffle work. 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[]) gives List<int[]> with one element. Use Integer[] or a stream with boxed().
  • null elements are allowed, unlike List.of.
  • List.of(...) is an alternative (Java 9+): truly immutable, rejects null, and does not share storage with an array. List.of(array) with a String[] also works through varargs, copying the elements.
  • Equality and hash code follow the List contract, so Arrays.asList(1, 2).equals(List.of(1, 2)) is true.
  • contains and indexOf are O(n); get and set are O(1).
  • Array covariance: Arrays.asList(new Integer[]{1}) is a List<Integer>, but a String[] stored in an Object[] variable can fail at run time when you set the wrong type (ArrayStoreException).