Immutability Guarantees of Factory Collections
You'll learn why singleton and empty collections from the Collections utility class are truly immutable and what happens when you try to modify them.
The Core Guarantee
Factory collections created by methods like Collections.singleton(), Collections.singletonList(), Collections.emptyList(), and similar methods are structurally immutable. This means they cannot be modified after creation—any attempt to add, remove, or replace elements will immediately throw an UnsupportedOperationException.
Unlike Collections.unmodifiableList() (which creates a read-only view that can change if the underlying collection changes), these factory collections are genuinely fixed. There's no backing collection that could be modified elsewhere.
Why This Matters
Think of these collections like laminated documents—permanently sealed and unchangeable. When you call Collections.singleton("Java"), you get a set with exactly one element, and that's how it will remain forever. Any modification method—add(), remove(), clear(), etc.—will reject your attempt.
Set<String> single = Collections.singleton("Java");
// single.add("Python"); // UnsupportedOperationException!
List<Integer> empty = Collections.emptyList();
// empty.add(42); // UnsupportedOperationException!
Map<String, Integer> singleMap = Collections.singletonMap("count", 1);
// singleMap.put("total", 5); // UnsupportedOperationException!
This immutability guarantee makes these collections safe to share across threads, return from methods without defensive copying, and use as constant values. You can trust they'll never change.
Key Takeaway: Singleton and empty collections from the Collections class are truly immutable—all modification attempts throw UnsupportedOperationException, providing stronger guarantees than unmodifiable views.