Sub topic 15
Unmodifiable Collections with of() Factories
Sometimes you want a collection that never changes, such as the days of the week or a fixed list of menu options. Java 9 added a quick way to make one. An unmodifiable collection is a collection that does not let you add, remove, or replace elements after you create it.
The of() factory methods
A factory method is a static method that builds an object for you, so you call it instead of using new. Java gives you three of them:
| Method | Creates | Example |
|---|---|---|
| `List.of(...)` | An unmodifiable list | `List.of("Mon", "Tue")` |
| `Set.of(...)` | An unmodifiable set | `Set.of("red", "blue")` |
| `Map.of(...)` | An unmodifiable map | `Map.of("Ana", 30, "Ben", 25)` |
For Map.of, you list the key and then its value, then the next key and its value, and so on.
A worked example
import java.util.List;
import java.util.Map;
public class ImmutableDemo {
public static void main(String[] args) {
List<String> days = List.of("Mon", "Tue", "Wed");
Map<String, Integer> ages = Map.of("Ana", 30, "Ben", 25);
System.out.println(days.get(0)); // Mon
System.out.println(ages.get("Ben")); // 25
try {
days.add("Thu");
} catch (UnsupportedOperationException e) {
System.out.println("List.of returns an unmodifiable list");
}
}
}Reading works as usual. You can call get, size, contains, and loop with for-each. Changing the collection fails. An UnsupportedOperationException is an error Java throws when you call a method the object does not allow. Calls like add, remove, set, put, and clear all throw it.
Why use them
- Safety. If you pass the list to another method, that method cannot change it by mistake.
- Short code. One line replaces creating a list and calling
addseveral times. - Clear intent. A reader can see right away that the data is fixed.
Rules to remember
Set.ofdoes not allow duplicates.Set.of("a", "a")throws anIllegalArgumentExceptionwhen you create it.Map.ofdoes not allow duplicate keys either, and it takes at most 10 key-value pairs. For more pairs, useMap.ofEntries(Map.entry("k", 1), ...).Set.ofandMap.ofdo not promise any iteration order. Do not depend on the order they print in.
When you need to change it
If you need a list you can edit, copy the fixed list into a new ArrayList:
import java.util.ArrayList;
import java.util.List;
public class CopyDemo {
public static void main(String[] args) {
List<String> fixed = List.of("Mon", "Tue");
List<String> editable = new ArrayList<>(fixed);
editable.add("Wed");
System.out.println(editable); // [Mon, Tue, Wed]
}
}The copy is a separate list, so fixed stays the same.
Exercise
What happens when this code runs: Set<String> s = Set.of("x", "y"); s.remove("x");
Show answer
It throws an UnsupportedOperationException, because sets made with Set.of cannot be changed.
Exercise
You need a list of colors that starts with "red" and "green" and later gets "blue" added. Write one line that creates it so the add will work.
Show answer
List<String> colors = new ArrayList<>(List.of("red", "green")); Copying into an ArrayList gives you a list you can edit, so colors.add("blue") works.
Exercise
Why does Set.of("a", "b", "a") fail?
Show answer
Set.of does not allow duplicate elements. It throws an IllegalArgumentException when the set is created.