Practical technical guides / Core IT: Java collections

Arrays.asList Returns a Fixed-Size View: add Throws, set Writes Through and List.of Rejects Null

Measured on JDK 23: Arrays.asList cannot grow but writes through to its array, List.of rejects even null queries, unmodifiableList is a live view. Which one to return.

By Sandeep Belgavi · Published 2026-11-06

Measured on JDK 23: Arrays.asList cannot grow but writes through to its array, List.of rejects even null queries, unmodifiableList is a live view. Which one to return.

The reading list that could not grow

The help-desk service at Belgavi's Book Store builds a reading list for each case: the books a customer bought, so an agent can suggest replacements. An old helper returned the list straight from the catalogue cache:

static List<String> legacyReadingList(String[] fromCatalog) {
    return Arrays.asList(fromCatalog);
}

A new feature appended a suggested title to that list and failed in production with UnsupportedOperationException. The fix that went in, new ArrayList<>(...) around the call, removed the exception. Nobody noticed the second problem until later: before the fix, a sort applied to the reading list for display had been reordering the catalogue cache's own array, because the list and the array were the same storage.

Java has six common ways to get a List from some elements, and they differ on four questions: can it grow, can elements be replaced, does it accept null, and is it a view of something else. This guide measures all six on JDK 23.0.2 with the companion probe.

Measured: what each factory allows

Each row starts from a fresh three-element list and tries one operation:

Factoryaddremovesetsortset(null)contains(null)
Arrays.asList(array)throwsthrowsokokokok
List.of(...)throwsthrowsthrowsthrowsthrowsthrows NPE
List.copyOf(list)throwsthrowsthrowsthrowsthrowsthrows NPE
Collections.unmodifiableList(list)throwsthrowsthrowsthrowsthrowsok
Stream.toList()throwsthrowsthrowsthrowsthrowsok
Collectors.toList()okokokokokok

"throws" means UnsupportedOperationException unless marked NPE. Three rows deserve a closer look.

Arrays.asList is a fixed-size view

The Javadoc is precise: Arrays.asList "returns a fixed-size list backed by the specified array. Changes made to the array will be visible in the returned list, and changes made to the list will be visible in the array." It implements the optional methods "except those that would change the size of the returned list". So set and sort work, and they write into the array:

asList.set writes the array: shelf[0]=ISBN-7
array write shows in the list: view.get(1)=ISBN-8
sorting the view sorts the array: [ISBN-2, ISBN-7, ISBN-8]

That is how the display sort reordered the cache. It also explains a quirk in the probe: removeIf with a predicate that matches nothing returns normally, while one that matches throws. The method only fails when it would actually change the size, so a test with data that never matches will not find the bug.

Two more traps sit in the same method. Arrays.asList(int[]) does not box: the probe prints a size of 1, because the list's single element is the int[] itself. Use Arrays.stream(qty).boxed().toList() instead. And the varargs form, Arrays.asList("a", "b"), creates a new array each call, so it is not a view of anything you can reach, but it is still fixed-size.

List.of and List.copyOf reject null, even in queries

The List interface documentation for unmodifiable lists says: "They disallow null elements. Attempts to create them with null elements result in NullPointerException." The probe shows the less obvious consequence: List.of("ISBN-1").contains(null) and indexOf(null) also throw NullPointerException, because the Collection contract allows a list that does not permit nulls to reject null queries. Code that probes a list with contains(x) where x may be null works with ArrayList and fails after a refactor to List.of.

List.copyOf takes a snapshot. After the probe's backing.add("ISBN-4"), a List.copyOf(backing) taken earlier still has two elements. It also avoids copying when it can: List.copyOf of a list that is already an unmodifiable List.of list returned the same instance in the probe, so defensive copies at every layer cost little.

Unmodifiable is not immutable

Collections.unmodifiableList "returns an unmodifiable view of the specified list". The view refuses changes, but it shows every change made through the original. In the probe, the view's size went from 2 to 3 when the backing ArrayList grew. Returning Collections.unmodifiableList(this.items) from a getter stops callers writing, not the owner changing the list under them; if a caller iterates while the owner modifies, it can still get a ConcurrentModificationException.

Stream.toList(), added in Java 16, returns an unmodifiable list that does accept nulls, which is the one way it differs from List.copyOf in the table. Its Javadoc says "calls to any mutator method will always cause UnsupportedOperationException to be thrown". Collectors.toList() happens to return an ArrayList on this JDK, but its Javadoc says "there are no guarantees on the type, mutability, serializability, or thread-safety of the List returned", so code that appends to its result depends on an implementation detail. When you need a mutable result, say so with Collectors.toCollection(ArrayList::new).

The shape to use for return values

For a value object that holds a list, copy once at the boundary and return the copy without wrapping it again:

static final class Shelf {
    private final List<String> isbns;

    Shelf(Collection<String> isbns) {
        this.isbns = List.copyOf(isbns);          // snapshot; rejects nulls with a clear stack trace
    }

    List<String> isbns() { return isbns; }        // already unmodifiable, no copy per call

    Shelf with(String isbn) {                      // changes produce a new value
        List<String> next = new ArrayList<>(isbns);
        next.add(Objects.requireNonNull(isbn, "isbn"));
        return new Shelf(next);
    }
}

This gives three guarantees the original helper lacked: later changes to the source do not leak in, callers cannot change the contents, and a null fails at construction, close to the bug, rather than in some later query. The cost is one copy per construction, not per read.

Choose by intent:

  • Returning data the caller must not change, and that will not change: List.copyOf or Stream.toList() (the latter if nulls are legitimate).
  • A read-only window onto a list you keep changing: Collections.unmodifiableList, and document that it is live.
  • A list the caller will change: return a new ArrayList and say so in the type or the name.
  • A quick fixed-size wrapper around an array you own: Arrays.asList, only where writing through to the array is intended.

Equality, sharing and threads

All six lists compare equal when they hold the same elements in the same order, because the List.equals contract is defined by contents, not by class. Tests that compare a returned list with List.of(...) therefore pass whatever factory produced it, which is convenient and also why such tests miss mutability bugs: they never try to write.

Sharing differs. A List.of or List.copyOf list cannot change after construction, so it is safe to publish to other threads without copying and safe to use as a cache value. An Arrays.asList view or an unmodifiable view is only as safe as the object behind it: if any code keeps a reference to the array or the backing list and writes to it, readers on other threads can see torn updates or a ConcurrentModificationException. When a value crosses a thread or cache boundary, copy it with List.copyOf at that boundary.

Failure modes to test for

  • Appending to a list you did not create. Any add on a list returned by another component deserves a check of where it came from.
  • Sorting for display. list.sort(...) on an Arrays.asList view reorders the source array; sort a copy.
  • Null queries after a refactor to List.of. Search for contains( and indexOf( on values that may be null.
  • Tests that never hit the size-changing path. removeIf and retainAll only fail on a fixed-size list when something matches.
  • Primitive arrays. Arrays.asList(int[]) is a list of one array.

Verification

The companion example is plain Java with no dependencies. run.sh compiles the probe and the checks, compares the probe output with expected-jdk23.txt recorded on JDK 23.0.2, and then runs eight checks against the Shelf class and the legacy helper: the legacy list cannot grow and writes through to the array; the shelf ignores later source changes, refuses caller changes, returns the same instance each call, rejects null at construction, produces a new value from with; and contains(null) on the copy throws. Most of the table is specified in the Javadoc; the Collectors.toList() row and the removeIf behaviour are what this JDK does, not guarantees.

Primary references and authorship

Original explanation and synthetic examples by Sandeep Belgavi. Companion code: Sandeep-BA/agent-decision-lab/examples/java/list_factory_semantics. Views are my own and do not represent any employer, past or present.