Java UnsupportedOperationException
A list created by List.of does not support adding or removing elements. An attempted change throws UnsupportedOperationException.
A simple example
UnsupportedOperationException
- Start with An immutable list containing A
- Do this Add B to a new copy
- Result New list A, B
Syntax
published.add(stop)
Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaAdd a stop to a published bus route
A planner starts with a published route that riders can already see. She needs to add the museum to a draft while keeping the original schedule available to other passengers.
import java.util.List;
import java.util.ArrayList;
class Main {
public static void main(String[] args) throws Exception {
var published = List.of("Station");
try {
published.add("Museum");
} catch (UnsupportedOperationException readOnly) {
var draft = new ArrayList<>(published);
draft.add("Museum");
System.out.println(draft);
}
}
}
[Station, Museum]
The published list rejects the update. A new ArrayList serves as the editable draft.
Prepare a draft without changing the timetable
A station manager wants to preview a new stop before printing the timetable. The draft and the published route must show different stop counts until the change is approved.
import java.util.List;
import java.util.ArrayList;
class Main {
public static void main(String[] args) throws Exception {
var published = List.of("Station");
var draft = new ArrayList<>(published);
draft.add("Museum");
System.out.println(published.size() + " published, " + draft.size() + " draft");
}
}
1 published, 2 draft
The mutable copy can grow independently of the published list.
Extend a draft shortlist
The school office is editing a mutable rehearsal list. Attempt to append one name to the roster. A published read-only list requires a working copy.
Code and output in Java
import java.util.*;
import java.io.*;
import java.nio.file.*;
import java.util.concurrent.*;
class Main {
public static void main(String[] args) throws Exception {
try {
new ArrayList<>(List.of("Ada")).add("Bo");
System.out.println("Name added");
} catch (UnsupportedOperationException problem) {
System.out.println("Make a working copy");
}
}
}
Name added
What to watch for
A mutable copy shares its element objects with the source. Here each stop is an immutable String.