Java Collection Copies and Views: Immutable Collections, Subranges and Unmodifiable Views
List.of, Set.of, Map.of and copyOf versus Collections.unmodifiableList, Arrays.asList, subList and range views, reversed views, newSetFromMap, and checked and synchronized wrappers. Learn which give independent copies and which give live windows, plus the null and ordering pitfalls.
kvi5hnuCode Sprout team member12 min readOn this page
The collections framework has only a handful of concrete classes, but you can get many more collection objects through views. You've already met one: map.keySet() doesn't copy the keys into a new set. It returns an object that implements Set and whose methods operate on the original map. This article tours every kind of copy and view in java.util. Small immutable collections, unmodifiable copies and views, subranges, reversed views, sets built from maps, checked views and synchronized views. The point of each is to know exactly whether you're holding a snapshot or a window.

Small unmodifiable collections: of and ofEntries
Since Java 9, the collection interfaces have static factory methods for small fixed collections:
List<String> names = List.of("Ada", "Grace", "Linus");
Set<Integer> primes = Set.of(2, 3, 5);
Map<String, Integer> scores = Map.of("Ada", 2, "Grace", 3, "Linus", 5);
List.of and Set.of have overloads for 0 to 10 arguments, which avoids allocating a varargs array in the common cases, plus a varargs version for more. Map.of can't have a varargs form, because keys and values alternate types, so it stops at 10 pairs. For more, use Map.ofEntries with Map.entry:
import static java.util.Map.*;
Map<String, Integer> scores = ofEntries(entry("Ada", 2), entry("Grace", 3), entry("Linus", 5));
These collections have some firm rules:
- Unmodifiable. Every mutator, including
add,put,remove,set,clearandsort, throwsUnsupportedOperationException. - No nulls. Passing
nullthrowsNullPointerException. So docontains(null)andindexOf(null)on these collections, which surprises people. - No duplicates in sets and map keys.
Set.of(1, 1)andMap.of("Ada", 4, "Ada", 2)throwIllegalArgumentException. This is a creation-time error, not silent deduplication. - Unspecified iteration order for
Set.ofandMap.of. The JDK deliberately scrambles it with a seed chosen at each JVM start, so two runs of the same program can printSet.of("a", "b", "c")differently. That is on purpose: it stops anyone from depending on an order that was never promised.
The implementations are compact. Small instances store elements in fields, and larger ones in an array. They are also value-based and thread-safe, because nothing can change. When you need a mutable collection, copy one: new ArrayList<>(List.of(…)).
Before Java 9, Collections provided several related helpers, and they're still useful:
Collections.nCopies(n, obj)returns an immutable list that appears to containncopies ofobjbut stores it only once.Collections.emptyList(),emptySet(),emptyMap()and friends, plussingletonList(x),singleton(x)andsingletonMap(k, v). These do acceptnull.
Don't confuse the Collections utility class with the Collection interface.
Unmodifiable copies: copyOf
List.copyOf, Set.copyOf and Map.copyOf (Java 10) make an unmodifiable snapshot of any collection:
List<String> frozen = List.copyOf(names); // later changes to names don't affect frozen
They follow the same rules as of: no null elements, and Set.copyOf silently drops duplicates. If the argument is already an unmodifiable collection of the right kind, copyOf returns it unchanged without copying. That makes defensive copying in constructors cheap:
record Team(String name, List<String> members) {
Team { members = List.copyOf(members); } // immutable record, no aliasing
}
Two related options come from streams. stream.toList() (Java 16) returns an unmodifiable list that, unlike List.of, allows nulls. Collectors.toUnmodifiableList(), toUnmodifiableSet() and toUnmodifiableMap() produce the same kind of collections as copyOf.
Unmodifiable views
Collections.unmodifiableList(list) and its siblings don't copy anything. They return a wrapper that forwards every read to the original collection and throws UnsupportedOperationException on every write. Use one when part of your code should look at a collection but not touch it:
private final List<String> staff = new ArrayList<>();
public List<String> getStaff() { return Collections.unmodifiableList(staff); }
There are wrappers for Collection, List, Set, SortedSet, NavigableSet, Map, SortedMap and NavigableMap. Java 21 added SequencedCollection, SequencedSet and SequencedMap versions.
Keep in mind what an unmodifiable view does not do:
- It doesn't make the collection immutable. The owner can still change it through the original reference, and the view shows those changes. In the demo, the view shows
Cyafterstaff.add("Cy"), while thecopyOfsnapshot doesn't. - It doesn't protect the elements. If the list holds mutable objects, callers can still call their setters.
- It exposes only the interface. The view of a
LinkedListis just aList, soaddFirstisn't available.
List.of / copyOf | Collections.unmodifiableList | |
|---|---|---|
| copies the data | yes, once | no |
| sees later changes to the source | no | yes |
| truly immutable | yes (shallow) | no, only read-only for this reference |
allows null | no | whatever the source allows |
| typical use | constants, records, return values | exposing internal state without copying |
Arrays.asList: a fixed-size view of an array
Arrays.asList(array) returns a List backed by the array. set writes into the array, and changes to the array show through the list. But the size is fixed, so add and remove throw UnsupportedOperationException. It is handy for passing an array to a method that expects a list. When you need an independent, growable list, wrap it: new ArrayList<>(Arrays.asList(a)).
Subranges
subList
list.subList(from, to) returns a view of positions from (inclusive) to to (exclusive), the same convention as String.substring:
List<Employee> group2 = staff.subList(10, 20);
The view is fully read-write, and every operation goes through to the original list. That makes subList a neat tool for range operations that List has no dedicated method for:
staff.subList(10, 20).clear(); // remove positions 10..19
Collections.sort(list.subList(0, 5)); // sort just the first five
int i = list.subList(5, list.size()).indexOf(x); // search from position 5
Ranges of sorted sets and maps
Sorted collections form subranges by value instead of position. SortedSet has subSet(from, to), headSet(to) and tailSet(from), which include the lower bound and exclude the upper. SortedMap has subMap, headMap and tailMap, which work on keys. NavigableSet and NavigableMap add overloads with boolean flags for each bound:
ages.subSet(21, true, 42, true); // 21 ≤ age ≤ 42
ages.headSet(30, true); // age ≤ 30
prices.tailMap("kiwi", false); // keys strictly after "kiwi"
These views are live and writable, with one restriction: inserting a value outside the range throws IllegalArgumentException.
Reversed views (Java 21)
Every SequencedCollection (lists, deques, LinkedHashSet, TreeSet) has reversed(), and every SequencedMap (LinkedHashMap, TreeMap) has a reversed() map. These are views, not copies. They cost O(1) to create and reflect later changes:
for (String s : collection.reversed()) { ... }
For a TreeSet this does the same thing as the older descendingSet(). For a list it replaces the old trick of looping with a ListIterator from the end.
Sets from boolean-valued maps
Some maps have abilities that their set counterparts lack. LinkedHashMap can evict its eldest entry, but LinkedHashSet can't. Collections.newSetFromMap(map) turns any Map<E, Boolean> into a Set<E>: adding e puts e → TRUE into the map, and removing e removes the key. Here's a set that keeps only the 100 most recently first-inserted strings. (Re-adding a string that's already present doesn't refresh its position, so this is FIFO eviction; pass new LinkedHashMap<>(16, 0.75f, true) for true LRU behaviour.)
Set<String> recent = Collections.newSetFromMap(new LinkedHashMap<>() {
protected boolean removeEldestEntry(Map.Entry<String, Boolean> eldest) {
return size() > 100;
}
});
Pass an empty map, and don't keep a reference to it. All changes should go through the set. The same trick turns WeakHashMap into a weak set and IdentityHashMap into an identity set. For a concurrent set, use ConcurrentHashMap.newKeySet().
Checked views
Generics are checked only at compile time, so raw types can pollute the heap by smuggling a wrong-typed element into a collection:
var strings = new ArrayList<String>();
ArrayList rawList = strings; // only a warning
rawList.add(new Date()); // succeeds! The failure comes later, far away, as a ClassCastException
Collections.checkedList(list, String.class) returns a view whose add checks the runtime type and throws ClassCastException immediately, at the line that caused the problem. It is a debugging tool: wrap a collection while you hunt down where bad elements come from. Checked views can only verify the raw class, so a checkedList of Pair<String> can't stop a Pair<Date>.
Synchronized views
Collections.synchronizedMap(new HashMap<>()), synchronizedList and the rest wrap a collection so that every method call is synchronized on the wrapper. One thread's put can't interleave with another thread's rehash. There are two big caveats:
- Iteration is not atomic. You must hold the lock yourself for the whole loop:
synchronized (map) { for (…) … }. The Javadoc requires this. - Compound actions aren't atomic. "Check, then put" sequences still race. In new code, prefer the concurrent collections (
ConcurrentHashMap,CopyOnWriteArrayList), which Part 10 covers.
A note on optional operations
Views make one design wart obvious. The Collection and Iterator interfaces mark many methods as optional operations, and a given view may throw UnsupportedOperationException for them. Purists would have preferred separate interfaces for read-only, fixed-size and fully mutable collections, but that would have tripled the number of interfaces. The designers chose a smaller API with a runtime check instead. It is a reasonable compromise for a library that must be simple, general and fast all at once. In your own designs, though, you rarely face constraints that extreme, so don't copy the "optional method" pattern. Design interfaces whose methods always work.
A complete example
import java.util.*;
import static java.util.Map.entry;
public class Solution {
static void attempt(String label, Runnable action) {
try {
action.run();
System.out.println(label + ": ok");
} catch (RuntimeException e) {
System.out.println(label + ": " + e.getClass().getSimpleName());
}
}
public static void main(String[] args) {
// 1. small unmodifiable collections
List<String> names = List.of("Ada", "Grace", "Linus");
Set<Integer> primes = Set.of(2, 3, 5);
Map<String, Integer> scores = Map.ofEntries(entry("Ada", 2), entry("Grace", 3), entry("Linus", 5));
System.out.println(names + ", primes sorted " + new TreeSet<>(primes) + ", Grace scored " + scores.get("Grace"));
attempt("names.add", () -> names.add("Ken"));
attempt("Set.of(13, null)", () -> Set.of(13, null));
attempt("Map.of duplicate keys", () -> Map.of("Ada", 4, "Ada", 2));
attempt("names.contains(null)", () -> names.contains(null));
int[] numbersArray = {2, 3, 5};
List<int[]> oops = List.of(numbersArray);
System.out.println("List.of(int[]) has size " + oops.size());
var mutable = new ArrayList<>(List.of("Ada", "Grace"));
mutable.add("Ken");
System.out.println("mutable copy " + mutable);
List<String> settings = Collections.nCopies(5, "DEFAULT");
System.out.println("nCopies " + settings);
// 2. copies versus views
var staff = new ArrayList<>(List.of("Ann", "Bo"));
List<String> copy = List.copyOf(staff);
List<String> view = Collections.unmodifiableList(staff);
staff.add("Cy");
System.out.println("original " + staff + ", copyOf " + copy + ", unmodifiable view " + view);
attempt("view.add", () -> view.add("Di"));
System.out.println("List.copyOf(List.of(...)) returns the same object: " + (List.copyOf(names) == names));
var unmodSet = Collections.unmodifiableSet(new TreeSet<>(Set.of("a", "b")));
var unmodColl = Collections.unmodifiableCollection(new TreeSet<>(Set.of("a", "b")));
System.out.println("unmodifiableSet equals " + unmodSet.equals(Set.of("a", "b"))
+ ", unmodifiableCollection equals " + unmodColl.equals(Set.of("a", "b")));
// 3. Arrays.asList: a fixed-size view of an array
String[] array = {"x", "y", "z"};
List<String> asList = Arrays.asList(array);
asList.set(0, "X"); // writes into the array
System.out.println("array after asList.set: " + Arrays.toString(array));
attempt("asList.add", () -> asList.add("w"));
// 4. subranges
var team = new ArrayList<>(List.of("a", "b", "c", "d", "e", "f", "g"));
List<String> middle = team.subList(2, 5); // c, d, e
middle.set(0, "C");
System.out.println("subList " + middle + " -> team " + team);
middle.clear(); // removes a range from team
System.out.println("after subList.clear(): team " + team);
List<String> stale = team.subList(0, 2);
team.add("z"); // structural change of the backing list
attempt("using subList after team.add", () -> stale.size());
var ages = new TreeSet<>(List.of(18, 21, 30, 42, 65));
System.out.println("subSet(21, 42) " + ages.subSet(21, 42) + ", subSet(21, true, 42, true) " + ages.subSet(21, true, 42, true)
+ ", headSet(30, true) " + ages.headSet(30, true));
var prices = new TreeMap<>(Map.of("apple", 3, "kiwi", 5, "mango", 7, "pear", 4));
System.out.println("headMap(mango) " + prices.headMap("mango") + ", tailMap(kiwi, false) " + prices.tailMap("kiwi", false));
attempt("ages.subSet(21, 42).add(99)", () -> ages.subSet(21, 42).add(99));
// 5. a set backed by a map: keeps the 3 most recently first-inserted words
Set<String> recent = Collections.newSetFromMap(new LinkedHashMap<>() {
private static final long serialVersionUID = 1L;
@Override protected boolean removeEldestEntry(Map.Entry<String, Boolean> eldest) {
return size() > 3;
}
});
for (String w : List.of("one", "two", "three", "four", "five")) recent.add(w);
System.out.println("newSetFromMap FIFO " + recent);
// 6. reversed views
var seq = new ArrayList<>(List.of(1, 2, 3));
List<Integer> rev = seq.reversed();
seq.add(4);
System.out.println("reversed view " + rev + ", TreeSet reversed " + ages.reversed());
// 7. checked views catch heap pollution at the insertion point
List<String> safe = Collections.checkedList(new ArrayList<>(), String.class);
@SuppressWarnings({"rawtypes", "unchecked"})
Runnable smuggle = () -> ((List) safe).add(42);
attempt("checkedList raw add(42)", smuggle);
// 8. synchronized view
Map<String, Integer> shared = Collections.synchronizedMap(new HashMap<>());
shared.put("hits", 1);
synchronized (shared) { // iteration needs the lock held manually
for (var e : shared.entrySet()) System.out.println("synchronized map entry " + e);
}
}
}
[Ada, Grace, Linus], primes sorted [2, 3, 5], Grace scored 3
names.add: UnsupportedOperationException
Set.of(13, null): NullPointerException
Map.of duplicate keys: IllegalArgumentException
names.contains(null): NullPointerException
List.of(int[]) has size 1
mutable copy [Ada, Grace, Ken]
nCopies [DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT]
original [Ann, Bo, Cy], copyOf [Ann, Bo], unmodifiable view [Ann, Bo, Cy]
view.add: UnsupportedOperationException
List.copyOf(List.of(...)) returns the same object: true
unmodifiableSet equals true, unmodifiableCollection equals false
array after asList.set: [X, y, z]
asList.add: UnsupportedOperationException
subList [C, d, e] -> team [a, b, C, d, e, f, g]
after subList.clear(): team [a, b, f, g]
using subList after team.add: ConcurrentModificationException
subSet(21, 42) [21, 30], subSet(21, true, 42, true) [21, 30, 42], headSet(30, true) [18, 21, 30]
headMap(mango) {apple=3, kiwi=5}, tailMap(kiwi, false) {mango=7, pear=4}
ages.subSet(21, 42).add(99): IllegalArgumentException
newSetFromMap FIFO [three, four, five]
reversed view [4, 3, 2, 1], TreeSet reversed [65, 42, 30, 21, 18]
checkedList raw add(42): ClassCastException
synchronized map entry hits=1
Note the subtle results. names.contains(null) throws instead of returning false. List.copyOf returns the very same object when given an immutable list. The unmodifiable view sees Cy, but the copy doesn't. Clearing a subList removes a range from team, and touching the old sublist after team.add fails fast. The sets built with Set.of are printed through a TreeSet, because their own iteration order changes from run to run.
Common questions
What is the difference between List.of, List.copyOf, Collections.unmodifiableList and stream.toList()?
List.of creates an unmodifiable list from the arguments. List.copyOf makes an unmodifiable snapshot of another collection. Collections.unmodifiableList wraps an existing list in a read-only view that still shows the owner's changes. stream.toList() returns an unmodifiable list, and unlike the first two, it accepts null elements.
Why does List.of(...).contains(null) throw an exception?
The immutable collections from of and copyOf reject null everywhere, including in queries such as contains and indexOf. Check for null yourself before calling, or use a collection that allows null.
Why does Arrays.asList(array).add(x) throw UnsupportedOperationException?
Arrays.asList returns a fixed-size view of the array. You can call set, but not add or remove. Wrap it in new ArrayList<>(Arrays.asList(array)) to get a growable list.
How do I delete a range of elements from a list?
Clear a sublist: list.subList(from, to).clear(). The change goes straight through to the original list. Don't keep the sublist after changing the original list's size, because the next access throws ConcurrentModificationException.
Are synchronized wrappers like Collections.synchronizedList still used?
Rarely in new code. They lock every call, but iteration and check-then-act sequences still need explicit synchronized blocks. The concurrent collections, such as ConcurrentHashMap and CopyOnWriteArrayList, are usually faster and easier to use correctly.
API reference
java.util.List, Set, Map (static factories)
| Method | Description |
|---|---|
List.of(E...), Set.of(E...) (Java 9) | unmodifiable list or set; no null; sets reject duplicates |
Map.of(K, V, ...) (up to 10 pairs), Map.ofEntries(Map.Entry...) (Java 9) | unmodifiable map; no null; duplicate keys rejected |
Map.entry(K k, V v) (Java 9) | unmodifiable entry |
List.copyOf(c), Set.copyOf(c), Map.copyOf(m) (Java 10) | unmodifiable copy; returns the argument if already suitable |
java.util.Collections
| Method | Description |
|---|---|
unmodifiableCollection, unmodifiableList, unmodifiableSet, unmodifiableSortedSet, unmodifiableNavigableSet, unmodifiableMap, unmodifiableSortedMap, unmodifiableNavigableMap, unmodifiableSequencedCollection / Set / Map (Java 21) | read-only views; mutators throw UnsupportedOperationException |
synchronizedCollection, synchronizedList, synchronizedSet, synchronizedSortedSet, synchronizedNavigableSet, synchronizedMap, synchronizedSortedMap, synchronizedNavigableMap | views whose methods are synchronized |
checkedCollection, checkedList, checkedSet, checkedSortedSet, checkedNavigableSet, checkedMap, checkedSortedMap, checkedNavigableMap, checkedQueue | views that throw ClassCastException on a wrongly typed insertion |
newSetFromMap(Map<E, Boolean> map) | set backed by an initially empty map |
nCopies(int n, E value) | immutable list of n identical values |
singleton, singletonList, singletonMap | immutable one-element collections |
emptyList, emptySet, emptySortedSet, emptyNavigableSet, emptyMap, emptySortedMap, emptyNavigableMap, emptyIterator, emptyListIterator, emptyEnumeration | empty immutable collections and iterators |
Range and reversed views
| Method | Description |
|---|---|
Arrays.asList(E... a) | modifiable, fixed-size list view of the array |
List.subList(int from, int to) | view of positions from (inclusive) to to (exclusive) |
SortedSet.subSet(from, to), headSet(to), tailSet(from) | views of a value range (lower bound inclusive, upper exclusive) |
NavigableSet.subSet(from, fromInclusive, to, toInclusive), headSet(to, inclusive), tailSet(from, inclusive) | range views with explicit bound inclusion |
SortedMap.subMap, headMap, tailMap; NavigableMap overloads with boolean flags | key-range views of a map |
SequencedCollection.reversed(), SequencedSet.reversed(), SequencedMap.reversed() (Java 21) | reverse-order views |
Summary
List.of,Set.of,Map.ofandofEntriescreate compact unmodifiable collections that rejectnulland duplicates.Set.ofandMap.ofhave deliberately random iteration order.copyOfmakes an unmodifiable snapshot.Collections.unmodifiable…makes a read-only view that still reflects changes to the original.Arrays.asListis a fixed-size view of an array.subListand the sorted-collection range methods are read-write windows. A sublist becomes invalid when its backing list is structurally changed.reversed()gives reverse-order views of any sequenced collection or map.newSetFromMapborrows map features for sets. Checked views catch heap pollution early. Synchronized views make single calls thread-safe, but not iteration or compound actions.
Practice Questions
What is the difference between List.copyOf(list) and Collections.unmodifiableList(list)?
copyOf copies the elements once into a new immutable list, so later changes to list aren't visible. unmodifiableList wraps the original: reads go through to it, so changes made via the original reference are visible, but writes through the wrapper throw.
Why might a test that prints Set.of("a", "b", "c") pass on one run and fail on the next?
The iteration order of Set.of and Map.of collections is randomized per JVM start. Compare with equals, or sort before printing, instead of comparing output strings.
How do you remove the elements at positions 5 through 9 from an ArrayList in one call?
list.subList(5, 10).clear();. The sublist is a view, so clearing it removes that range from the backing list, with a single array shift.
Arrays.asList(arr).add(x) throws. Why, and how do you get a growable list?
The list is a fixed-size view of the array, so it can't change size. Use new ArrayList<>(Arrays.asList(arr)).
Is it safe to iterate over a Collections.synchronizedList from several threads without extra code?
No. Each individual method is synchronized, but an iteration consists of many calls. Hold the lock for the whole loop with synchronized (list) { for (...) ... }, or use a concurrent collection such as CopyOnWriteArrayList.
Previous: Java Map Views and Special Maps: LinkedHashMap, EnumMap, WeakHashMap and IdentityHashMap
Next: Java Collections Algorithms: Sorting, Shuffling, Binary Search and Bulk Operations
Related reading
- Java Map Views and Special Maps: LinkedHashMap, EnumMap, WeakHashMap and IdentityHashMap
- Java Maps: HashMap, TreeMap and Updating Map Entries
- Java Queues and Deques: ArrayDeque, LinkedList and PriorityQueue
- Java HashSet and TreeSet: Hash Tables, Hash Codes and Sorted Sets
- Java LinkedList vs ArrayList: Linked Lists, ListIterator and Array Lists

More in Core Java I
Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads
Share data between Java threads without bugs: memory visibility and volatile, final fields, AtomicInteger and compareAndSet, LongAdder, lazy holder initialization, safe publication, lock-ordering deadlocks, ThreadLocal, InheritableThreadLocal and ScopedValue.
Java Condition Objects and the synchronized Keyword: await, signalAll, wait and notify
Make threads wait for a condition safely with Condition.await and signalAll, then learn Java's built-in alternative: synchronized methods and blocks, intrinsic locks, wait and notifyAll, choosing lock objects, client-side locking, and the monitor concept.
Java Race Conditions and ReentrantLock: Synchronizing Shared Data
Why unsynchronized threads corrupt shared data, shown step by step with a lost-update race, and how to fix it with ReentrantLock: the lock/try/finally idiom, critical sections, reentrancy and hold counts, tryLock, fair locks, and the mistakes that cause bugs.
Java invokeAll, invokeAny and Fork-Join: Running Groups of Tasks
Coordinate many concurrent tasks in Java: invokeAll to wait for every result, invokeAny to take the first success, timeouts, ExecutorCompletionService for results in completion order, structured concurrency, and the fork-join framework with RecursiveTask, RecursiveAction and work stealing.
Discussion
Sign in to ask a question or share what you learned.