Fixed and unmodifiable lists
35 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)Not every List can be changed. List.of, List.copyOf and Collections.unmodifiableList give lists that refuse every change, and Arrays.asList gives a list whose size is fixed. They all look like a normal List, so the refusal only shows up when the program runs.
Three kinds of lists
An unmodifiable list is a List that refuses every change: add, remove, set and sort all throw UnsupportedOperationException. List.of, List.copyOf and Collections.unmodifiableList give such lists. Reading works as usual.
A modifiable list, like ArrayList, allows everything: add, remove, set, sort. A fixed-size list allows set but not add or remove. An unmodifiable list allows no change at all.
List<String> open = new ArrayList<>(List.of("Asha", "Ravi"));open.add("Meena"); // fine: modifiableList<String> fixed = Arrays.asList("Asha", "Ravi");fixed.set(0, "Anu"); // fine: the size stays the samefixed.add("Meena"); // UnsupportedOperationExceptionList<String> locked = List.of("Asha", "Ravi");locked.set(0, "Anu"); // UnsupportedOperationExceptionAll three have the type List, and the List interface has an add method. So the compiler accepts list.add(x) on any of them. A forbidden change throws UnsupportedOperationException at run time. It is unchecked, like IndexOutOfBoundsException.
new ArrayList<>(...)→ modifiableArrays.asList(...)→ fixed size:setyes,add/removenoList.of(...),List.copyOf(...)→ unmodifiableCollections.unmodifiableList(list)→ unmodifiable view of another list
List.of and List.copyOf
List.of("Maths", "Physics") builds an unmodifiable list from the values you give. List.copyOf(otherList) builds an unmodifiable copy of another collection: a snapshot.
Example 1 · Crash: List.of cannot change
import java.util.List;
public class FixedSubjectsDemo { public static void main(String[] args) { List<String> subjects = List.of("Maths", "Physics", "Chemistry"); System.out.println("Subjects: " + subjects); System.out.println("First: " + subjects.get(0) + ", count " + subjects.size());
subjects.add("Biology"); System.out.println("Never printed"); }}Subjects: [Maths, Physics, Chemistry] First: Maths, count 3 Exception in thread "main" java.lang.UnsupportedOperationException at java.base/java.util.ImmutableCollections.uoe(ImmutableCollections.java:142) at java.base/java.util.ImmutableCollections$AbstractImmutableCollection.add(ImmutableCollections.java:147) at FixedSubjectsDemo.main(FixedSubjectsDemo.java:9)
What this code does
- Reading works as usual. The compiler accepts
addtoo, becausesubjectshas the typeList. - At run time the list refuses:
UnsupportedOperationException, thrown fromImmutableCollections, the JDK class behindList.of. Line 9 is theaddcall.
List.of is the neatest way to write a fixed group of values, like the days of the week or the default subjects. Later changes to the other list do not reach a List.copyOf snapshot.
Both refuse null: List.of("a", null) throws NullPointerException at once. Even contains(null) on such a list throws. If you really need nulls in a list, use an ArrayList.
Arrays.asList: a fixed-size view of an array
A fixed-size list is a List whose size cannot change: set works, but add and remove throw UnsupportedOperationException. Arrays.asList(array) gives one, because an array cannot grow or shrink.
Arrays.asList(array) does not copy the array. It wraps it in a List that reads and writes the same array. This is called a view.
Example 2 · Arrays.asList writes through to the array
import java.util.Arrays;import java.util.List;
public class SeatViewDemo { public static void main(String[] args) { String[] seats = { "Aarav", "Diya", "Kabir" }; List<String> seatList = Arrays.asList(seats);
seatList.set(0, "Meera"); System.out.println("Array after list.set: " + Arrays.toString(seats));
seats[2] = "Rohan"; System.out.println("List after array change: " + seatList);
try { seatList.add("Tara"); } catch (UnsupportedOperationException e) { System.out.println("add failed: " + e.getClass().getSimpleName()); } System.out.println("Size is still " + seatList.size()); }}Array after list.set: [Meera, Diya, Kabir] List after array change: [Meera, Diya, Rohan] add failed: UnsupportedOperationException Size is still 3
What this code does
- The list and the array share the same storage: a change through either one shows in the other.
setis allowed because the size stays the same;addwould need a bigger array, so it throws.
Example 3 · Fix: make a changeable copy
import java.util.ArrayList;import java.util.Arrays;import java.util.Collections;import java.util.List;
public class ElectiveDemo { public static void main(String[] args) { List<String> core = List.of("Maths", "Physics", "Chemistry");
List<String> mySubjects = new ArrayList<>(core); mySubjects.add("Computer Science"); Collections.sort(mySubjects); System.out.println("My subjects: " + mySubjects); System.out.println("Core unchanged: " + core);
String[] cities = { "Pune", "Agra" }; List<String> trip = new ArrayList<>(Arrays.asList(cities)); trip.add("Kochi"); trip.set(0, "Puri"); System.out.println("Trip: " + trip); System.out.println("Array unchanged: " + Arrays.toString(cities)); }}My subjects: [Chemistry, Computer Science, Maths, Physics] Core unchanged: [Maths, Physics, Chemistry] Trip: [Puri, Agra, Kochi] Array unchanged: [Pune, Agra]
What this code does
new ArrayList<>(core)copies the items into a normal list, which can add and sort.new ArrayList<>(Arrays.asList(cities))gives a list that can grow and is no longer tied to the array.- The originals stay as they were, because every change happened in the copy.
Example 4 · Nulls: List.of says no, Arrays.asList says yes
import java.util.Arrays;import java.util.List;
public class NullRulesDemo { public static void main(String[] args) { List<String> roomies = Arrays.asList("Aarav", null, "Kabir"); System.out.println("asList with null: " + roomies); System.out.println("Empty bed at " + roomies.indexOf(null));
try { List<String> fixed = List.of("Aarav", null, "Kabir"); } catch (NullPointerException e) { System.out.println("List.of refused null"); }
List<String> names = List.of("Aarav", "Kabir"); try { names.contains(null); } catch (NullPointerException e) { System.out.println("Even contains(null) throws"); } }}asList with null: [Aarav, null, Kabir] Empty bed at 1 List.of refused null Even contains(null) throws
What this code does
Arrays.asListis a view of an array, and arrays can holdnull, so it accepts and findsnull.List.ofchecks every value when it is built and throwsNullPointerExceptionfor anull.- Lists from
List.ofandList.copyOfalso throw oncontains(null). Avoidnullitems in lists; they cause bugs like this.
list.set(0, x) changes array[0], and changing array[0] changes what list.get(0) returns. add and remove throw UnsupportedOperationException. Unlike List.of, it allows null items and set.
To get a normal list from an array, copy it: new ArrayList<>(Arrays.asList(array)). The Utilities & Best Practices module shows more array-to-list traps.
Fix the error
Get a list you can change
Read the real error, then pick the line that fixes it.
Round 1 of 3
The store adds a subject to its fixed subject list.
Error
Exception in thread "main" java.lang.UnsupportedOperationException at java.base/java.util.ImmutableCollections.uoe(ImmutableCollections.java:142) at java.base/java.util.ImmutableCollections$AbstractImmutableCollection.add(ImmutableCollections.java:147)
Collections.unmodifiableList: a read-only view
Collections.unmodifiableList(list) wraps an existing list. Code that has only the wrapper cannot change anything, but the owner can still change the inner list, and the wrapper shows those changes.
Example 5 · A view vs a snapshot
import java.util.ArrayList;import java.util.Collections;import java.util.List;
public class ViewVsCopyDemo { public static void main(String[] args) { List<String> notices = new ArrayList<>(); notices.add("Fees due 10th");
List<String> board = Collections.unmodifiableList(notices); List<String> printout = List.copyOf(notices);
notices.add("Holiday on Friday");
System.out.println("Owner's list: " + notices); System.out.println("Read-only view: " + board); System.out.println("Snapshot copy: " + printout);
try { board.add("Fake notice"); } catch (UnsupportedOperationException e) { System.out.println("Cannot post through the view"); } }}Owner's list: [Fees due 10th, Holiday on Friday] Read-only view: [Fees due 10th, Holiday on Friday] Snapshot copy: [Fees due 10th] Cannot post through the view
What this code does
- The view (
board) shows the holiday notice added later, because it reads the owner's list. - The copy (
printout) was made before that add, so it still has only one notice. - Neither can be changed by its holder; only the owner of
noticescan add.
Example 6 · Read-only list, changeable objects
import java.util.List;
class Wallet { private final String owner; private int balance;
Wallet(String owner, int balance) { this.owner = owner; this.balance = balance; }
void spend(int amount) { balance = balance - amount; }
@Override public String toString() { return owner + ": Rs. " + balance; }}
public class ShallowReadOnlyDemo { public static void main(String[] args) { List<Wallet> wallets = List.of(new Wallet("Riya", 500), new Wallet("Sahil", 300)); System.out.println("Before: " + wallets);
wallets.get(0).spend(200);
System.out.println("After: " + wallets); }}Before: [Riya: Rs. 500, Sahil: Rs. 300] After: [Riya: Rs. 300, Sahil: Rs. 300]
What this code does
- The list cannot gain, lose or swap wallets. But
get(0)returns the realWalletobject, and itsspendmethod changes it. - An unmodifiable list protects the list, not the objects inside. Immutable items (records with no setters) make the whole thing fixed.
The wrapper is a view, not a copy. So choose by what the caller should see. A view shows live data that the caller cannot edit, like a notice board. A copy (List.copyOf) freezes the data at the moment it was made, like a printout.
Need to change a read-only list? Make your own modifiable copy: new ArrayList<>(readOnly). Then change the copy freely.
Next step
Check your understanding
12 quick questions