Tech Interview RoomStudy guides

Java 17

Java 17: Immutable and unmodifiable collections. Compare Arrays.asList, unmodifiableList, List.of, List.copyOf and Stream.toList.

Intermediate · 2 min read · Lesson 4 of 8 in Java 17

Problem

Your class receives a list and must expose it without letting callers (or the original owner) change it. Interviewers expect you to know exactly how each factory behaves.

Approach 1: Legacy wrappers, Arrays.asList and Collections.unmodifiableList (Java 1.2)

Arrays.asList is fixed-size but writable (set works and writes through to the array). unmodifiableList is a read-only view: it blocks your writes, but changes to the underlying list still show through.

java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

class LegacyWrappers {
    static String attempt(Runnable r) {
        try { r.run(); return "allowed"; }
        catch (UnsupportedOperationException e) { return "UnsupportedOperation"; }
        catch (NullPointerException e) { return "NullPointer"; }
    }

    static void show() {
        List<String> asList = Arrays.asList("a", "b");
        System.out.println("asList.set: " + attempt(() -> asList.set(0, "x")) + ", asList.add: " + attempt(() -> asList.add("c")));
        List<String> source = new ArrayList<>(List.of("a", "b"));
        List<String> view = Collections.unmodifiableList(source);
        System.out.println("view.add: " + attempt(() -> view.add("c")));
        source.add("c");
        System.out.println("view sees the source change: " + view);          // [a, b, c]
    }
}

Approach 2: Immutable factories, List.of and List.copyOf (Java 9 and 10)

Truly immutable, compact, and null-hostile: nulls are rejected on creation and even contains(null) throws. copyOf copies, so later changes to the source do not leak in, and it returns the same instance if the input is already immutable.

java
import java.util.ArrayList;
import java.util.List;

class ImmutableFactories {
    static void show() {
        List<String> source = new ArrayList<>(List.of("a", "b"));
        List<String> copy = List.copyOf(source);
        source.add("c");
        System.out.println("copy unaffected: " + copy);                                                 // [a, b]
        List<String> of = List.of("a", "b");
        System.out.println("of.add: " + LegacyWrappers.attempt(() -> of.add("c")));                     // UnsupportedOperation
        System.out.println("of.contains(null): " + LegacyWrappers.attempt(() -> of.contains(null)));    // NullPointer
        System.out.println("List.of(null): " + LegacyWrappers.attempt(() -> List.of((String) null)));   // NullPointer
        System.out.println("copyOf(immutable) is same instance: " + (List.copyOf(of) == of));          // true
    }
}

Approach 3: Collecting streams, Collectors.toUnmodifiableList vs Stream.toList (Java 10 and 16)

toUnmodifiableList() rejects nulls like List.of; Stream.toList() is unmodifiable but allows nulls; Collectors.toList() gives a mutable list (in practice an ArrayList).

java
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

class StreamCollectors {
    static void show() {
        List<String> withNull = Stream.of("a", null).toList();
        System.out.println("Stream.toList with null: " + withNull);                                           // [a, null]
        System.out.println("toUnmodifiableList with null: "
            + LegacyWrappers.attempt(() -> Stream.of("a", null).collect(Collectors.toUnmodifiableList())));  // NullPointer
        List<String> unmodifiable = Stream.of("a", "b").collect(Collectors.toUnmodifiableList());
        System.out.println("toUnmodifiableList.add: " + LegacyWrappers.attempt(() -> unmodifiable.add("z")));   // UnsupportedOperation
        List<String> mutable = Stream.of("a").collect(Collectors.toList());
        mutable.add("b");
        System.out.println("Collectors.toList is mutable: " + mutable);                                       // [a, b]
    }
}

Approach 4: A defensive getter in your own class (the design answer)

Copy once on the way in with List.copyOf, then return the field directly: O(1), safe, and nulls rejected early. Compare with copying on every call or returning a view.

java
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

final class Team {
    private final List<String> members;

    Team(List<String> members) {
        this.members = List.copyOf(members);                 // optimal: immutable snapshot, rejects nulls
    }

    List<String> membersCopyEachTime() { return new ArrayList<>(members); }               // feasible: O(n) per call
    List<String> membersView() { return Collections.unmodifiableList(members); }         // safe here only because members is private
    List<String> members() { return members; }                                           // optimal: already immutable, O(1)
}

class CollectionDemo {
    public static void main(String[] args) {
        LegacyWrappers.show();
        ImmutableFactories.show();
        StreamCollectors.show();
        List<String> input = new ArrayList<>(List.of("asha", "ravi"));
        Team t = new Team(input);
        input.add("intruder");
        System.out.println(t.members() + " " + t.membersCopyEachTime() + " " + t.membersView());   // [asha, ravi] x3
        try { t.members().add("x"); } catch (UnsupportedOperationException e) { System.out.println("immutable"); }
    }
}

Feasible → optimal

  • Returning a fresh ArrayList each time is safe but costs O(n) per call.
  • Collections.unmodifiableList is O(1) but only a view: if anyone still holds the original list, they can change what you expose.
  • List.copyOf in the constructor plus returning the field is optimal: one O(n) copy, then O(1) safe access, and nulls rejected early.
  • Stream.toList() for stream results when nulls may occur; Collectors.toList() when you need a mutable list.

Follow-up questions interviewers ask

Try answering each one before you open it.

Are List.of collections deeply immutable?

No. The list structure cannot change, but the elements themselves can, if they are mutable objects (List.of(new StringBuilder())). Deep immutability requires immutable element types such as String, records with immutable components, or java.time values.

Why does List.of reject null?

Nulls in collections are a common source of bugs, and banning them lets the implementations be compact and fast and makes contains(null) meaningless (it throws). If you need nulls, use Arrays.asList, Stream.toList() or a mutable list, but usually it is better to represent absence explicitly.