Sub topic 15
Unmodifiable Collections with of() Factories
So far you have built collections by creating an empty ArrayList, HashSet, or HashMap and calling add or put many times. That works, but often you already know every element when you write the code. Examples are the days of the week, a list of allowed file types, or a fixed price table. In those cases Java gives you shorter tools: List.of, Set.of, and Map.of.
These methods create unmodifiable collections. An unmodifiable collection is a collection that cannot be changed after it is created. You can read from it, but you cannot add, remove, or replace elements.
This chapter shows how to create these collections, what happens when you try to change them, the rules they enforce, and how to get a changeable copy when you need one.
What a Factory Method Is
A factory method is a static method that creates and returns a new object for you. You call it on the interface or class name, not on an object. List.of(...) is a factory method on the List interface. You do not write new and you do not pick an implementation class. Java picks a hidden, internal class for you.
These factories were added in Java 9. If you use Java 8 or older, they will not compile.
Creating Lists, Sets, and Maps in One Line
Here is the basic pattern for all three.
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");
}
}
}Look at three things in this code:
List.of("Mon", "Tue", "Wed")makes a list of three strings in that order.Map.of("Ana", 30, "Ben", 25)takes arguments in pairs: key, value, key, value.- Calling
days.add("Thu")compiles fine but fails when the program runs. It throws an UnsupportedOperationException. That exception means "this collection does not allow this operation."
Reading methods such as get, size, contains, and for-each loops all work normally.
Why You Would Want a Collection That Cannot Change
Not being able to change something can sound like a drawback. It actually helps in several ways:
- Safety. If you pass a list to another method, that method cannot change your data by accident.
- Clear intent. A reader sees
List.ofand knows the data is fixed. - Less code. One line replaces several
addcalls. - Safe sharing. Many parts of a program can read the same fixed collection at once without any risk.
A common use is a constant, which is a static final field that holds data that never changes:
import java.util.Set;
public class Upload {
private static final Set<String> ALLOWED = Set.of("png", "jpg", "gif");
public static void main(String[] args) {
System.out.println(ALLOWED.contains("png")); // true
System.out.println(ALLOWED.contains("exe")); // false
}
}The Rules These Factories Enforce
The of factories are stricter than ArrayList, HashSet, and HashMap. Break a rule and you get an exception at the moment you create the collection.
| Rule | Applies to | What happens if broken |
|---|---|---|
| No changes after creation | List, Set, Map | `UnsupportedOperationException` |
| No `null` elements, keys, or values | List, Set, Map | `NullPointerException` |
| No duplicate elements | Set | `IllegalArgumentException` |
| No duplicate keys | Map | `IllegalArgumentException` |
| Iteration order is not guaranteed | Set, Map | No error, but the order may differ between runs |
Duplicates are fine in List.of, because lists allow duplicates. Duplicates in Set.of count as an error and are not silently dropped. That is different from HashSet.add, which just returns false.
This program triggers each creation error so you can see them:
import java.util.List;
import java.util.Map;
import java.util.Set;
public class RulesDemo {
public static void main(String[] args) {
System.out.println(List.of("a", "a", "b")); // [a, a, b] duplicates are fine
try {
List.of("a", null);
} catch (NullPointerException e) {
System.out.println("null is not allowed");
}
try {
Set.of("x", "x");
} catch (IllegalArgumentException e) {
System.out.println("Set.of rejects duplicates: " + e.getMessage());
}
try {
Map.of("k", 1, "k", 2);
} catch (IllegalArgumentException e) {
System.out.println("Map.of rejects duplicate keys: " + e.getMessage());
}
}
}Maps With More Than Ten Entries
Map.of accepts at most 10 key-value pairs. For bigger maps, use Map.ofEntries together with Map.entry. Each Map.entry(key, value) builds one pair.
import java.util.Map;
public class EntriesDemo {
public static void main(String[] args) {
Map<String, Integer> prices = Map.ofEntries(
Map.entry("apple", 3),
Map.entry("bread", 2),
Map.entry("milk", 1)
);
System.out.println(prices.get("bread")); // 2
System.out.println(prices.size()); // 3
}
}You can use Map.ofEntries for small maps too. Some people like it because the key and value sit together inside each entry, which is easier to read.
Getting a Changeable Copy
Sometimes you start with fixed data but later need to change it. You do not modify the unmodifiable collection. You copy it into a normal one. Every standard implementation has a constructor that accepts another collection.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class CopyDemo {
public static void main(String[] args) {
List<String> fixed = List.of("red", "green");
List<String> editable = new ArrayList<>(fixed);
editable.add("blue");
System.out.println(editable); // [red, green, blue]
System.out.println(fixed); // [red, green] unchanged
Map<String, Integer> start = Map.of("a", 1);
Map<String, Integer> counts = new HashMap<>(start);
counts.put("b", 2);
System.out.println(counts.get("b")); // 2
}
}You can also go the other way. List.copyOf, Set.copyOf, and Map.copyOf (Java 10 and later) take any collection and return an unmodifiable copy. Later changes to the original do not show up in the copy.
import java.util.ArrayList;
import java.util.List;
public class CopyOfDemo {
public static void main(String[] args) {
List<String> work = new ArrayList<>();
work.add("draft");
List<String> snapshot = List.copyOf(work);
work.add("final");
System.out.println(work); // [draft, final]
System.out.println(snapshot); // [draft]
}
}Edge Case: Unmodifiable Is Shallow
"Unmodifiable" applies only to the collection itself. You cannot add, remove, or replace elements. But if an element is an object that can change, that object can still change. This is called shallow immutability: the outer container is locked, but the things inside it are not.
import java.util.ArrayList;
import java.util.List;
public class ShallowDemo {
public static void main(String[] args) {
List<String> inner = new ArrayList<>();
inner.add("one");
List<List<String>> outer = List.of(inner);
outer.get(0).add("two"); // allowed: changes the inner list
System.out.println(outer); // [[one, two]]
try {
outer.add(new ArrayList<>()); // not allowed: changes the outer list
} catch (UnsupportedOperationException e) {
System.out.println("outer list is unmodifiable");
}
}
}If you need data that can never change at any level, store elements that cannot change themselves. String, Integer, and objects whose fields are all final are good choices.
Summary
List.of,Set.of, andMap.ofcreate unmodifiable collections in one line (Java 9 and later).- Any attempt to change them throws
UnsupportedOperationExceptionwhen the code runs. - They reject
null.Set.ofrejects duplicate elements andMap.ofrejects duplicate keys. Map.ofholds at most 10 pairs. UseMap.ofEntriesfor more.- Copy into
new ArrayList<>(...)ornew HashMap<>(...)to get a changeable version. UsecopyOfto get an unmodifiable snapshot. - Unmodifiable is shallow. Elements that can change are still changeable.
Exercise
What does this code print, or what exception does it throw? Set<Integer> s = Set.of(1, 2, 2); System.out.println(s.size());
Show answer
It throws IllegalArgumentException when Set.of is called, because Set.of does not allow duplicate elements. The println line never runs. A HashSet would quietly keep one 2, but Set.of treats the duplicate as an error.
Exercise
You have List<String> colors = List.of("red", "blue"); and you need to add "green". Write one or two lines that give you a list containing all three colors.
Show answer
Copy into a changeable list, then add: List<String> more = new ArrayList<>(colors); more.add("green"); The original colors list stays unchanged as [red, blue].
Exercise
A program stores 12 product prices in a fixed map. Why does Map.of not work here, and what should you use instead?
Show answer
Map.of accepts at most 10 key-value pairs. Use Map.ofEntries with one Map.entry("name", price) per product. It also creates an unmodifiable map and has no fixed limit on the number of entries.
Exercise
Given List<StringBuilder> list = List.of(new StringBuilder("hi"));, does list.get(0).append("!") throw an exception? Explain.
Show answer
No. The list is unmodifiable, but only shallowly. You cannot add, remove, or replace its elements. The StringBuilder inside it can still change, so append works and the element becomes "hi!".