Java core learning path Level 1 This level · 20 of 34
Easy java java-21

What is the difference between List.of() and Arrays.asList()?

The 30 second answer

List.of, from Java 9, gives a truly unmodifiable list: add, set and remove all throw, and it rejects null elements. Arrays.asList gives a fixed-size view over an array: I can't add or remove, but I can set an element, and that change writes through to the original array. Arrays.asList also allows nulls. So List.of is safer for constants and return values.

Could you say this in an interview?
List.of(...)Arrays.asList(...)
add / removethrows UnsupportedOperationExceptionthrows UnsupportedOperationException
setthrowsallowed, writes through to the array
null elementsNullPointerExceptionallowed
backed by arraynoyes (a view)
contains(null)throws NullPointerExceptionworks
String[] arr = {"a", "b"};
List<String> view = Arrays.asList(arr);
view.set(0, "z");              // arr[0] is now "z"
List.of("a", "b").set(0, "z"); // UnsupportedOperationException

Related: List.copyOf (Java 10) makes an unmodifiable copy of any collection, and Stream.toList() (Java 16) returns an unmodifiable list. Collections.unmodifiableList is only a read-only view; changes to the underlying list are still visible through it.

Sources (3)
  1. List Javadoc: Unmodifiable Listsdocs.oracle.com
  2. Arrays.asList Javadocdocs.oracle.com
  3. JEP 269: Convenience Factory Methods for Collectionsopenjdk.org
Previous
Next