Library contents

Java UnsupportedOperationException

A list created by List.of does not support adding or removing elements. An attempted change throws UnsupportedOperationException.

A simple example

UnsupportedOperationException

  1. Start with An immutable list containing A
  2. Do this Add B to a new copy
  3. Result New list A, B
Creating a new collection keeps the original list intact.

Syntax

Java syntax
published.add(stop)
Run these examples in Java

Save one example at a time as Main.java. Use JDK 21.

java Main.java

Add 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.

From the programvar published = List.of("Station")
Result[Station, Museum]
Main.java
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);
        }
    }
}
Output
[Station, Museum]

The published list rejects the update. A new ArrayList serves as the editable draft.

Advertisements

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.

From the programvar published = List.of("Station")
Result1 published, 2 draft
Main.java
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");
    }
}
Output
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.

GivenEditable list [Ada]
Worked resultName added
Code and output in Java
Java source
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");
        }
    }
}
Output
Name added

What to watch for

A mutable copy shares its element objects with the source. Here each stop is an immutable String.

Documentation for UnsupportedOperationException