Converting arrays and lists

Collections · lesson 18 of 42 · 3 min read

Move between arrays and lists in both directions without hitting the asList traps.

Open this lesson in the learning hub

Key points

  • Arrays.asList(arr) is a fixed-size view: set writes through to the array, add throws.
  • For a real mutable list write new ArrayList<>(Arrays.asList(arr)). For a frozen one, List.of(arr).
  • Going back: list.toArray(new String[0]). The zero-length array is the idiomatic and fastest form.
  • Arrays.asList(intArray) returns a list of one element, the array itself. Primitives are not elements.
  • For primitives use Arrays.stream(a).boxed().toList() and list.stream().mapToInt(Integer::intValue).toArray().

Example

import java.util.*;

public class Main {
    public static void main(String[] args) {
        String[] arr = {"x", "y", "z"};

        List<String> fixed = Arrays.asList(arr);
        List<String> mutable = new ArrayList<>(Arrays.asList(arr));
        List<String> frozen = List.of(arr);
        mutable.add("w");

        System.out.println("Arrays.asList     : " + fixed + "   (fixed size, writes through)");
        System.out.println("new ArrayList<>   : " + mutable + "   (independent, growable)");
        System.out.println("List.of(arr)      : " + frozen + "   (immutable copy)");

        String[] back = mutable.toArray(new String[0]);
        System.out.println("toArray(new T[0]) : " + Arrays.toString(back));

        int[] prims = {3, 1, 2};
        List<Integer> boxed = Arrays.stream(prims).boxed().toList();
        System.out.println("int[] to List     : " + boxed);
        int[] again = boxed.stream().mapToInt(Integer::intValue).toArray();
        System.out.println("List to int[]     : " + Arrays.toString(again));

        System.out.println("asList(int[]).size: " + Arrays.asList(prims).size() + "   (one element: the array)");

        fixed.set(0, "X");
        System.out.println("asList write-thru : " + Arrays.toString(arr) + "   (the array changed)");
    }
}

Arrays.asList is a view, new ArrayList is a copy, List.of is frozen. Pick the one you meant.

This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Collections course, and every lesson in it is listed on the Collections contents page.