In Java, Collections.unmodifiableCollection(c) returns a read-only view of the collection c. You can read, loop, and search through the view, but every method that would change it throws UnsupportedOperationException.
It is the most general of the unmodifiable* wrappers: it works for any Collection, such as an ArrayDeque or a PriorityQueue, when you do not need list, set, or map behavior on the result.
A static method of the java.util.Collections utility class, available since Java 1.2. Call it on the class name, as in Collections.unmodifiableCollection(...), after import java.util.Collections;. You never create a Collections object.
Syntax
Wrap the collection you want to protect.
Java
private final ArrayDeque<String> messages = new ArrayDeque<>();
public Collection<String> getMessages() {
return Collections.unmodifiableCollection(messages);
}
Call
What it does
unmodifiableCollection(c)
Read-only view; size, contains, iteration all work.
view.add(x) / view.clear()
Throws UnsupportedOperationException.
view.iterator().remove()
Also throws; there is no back door.
Collection<Number> v = unmodifiableCollection(ints)
Can widen the element type, because nothing can be added.
Available since Java 1.2. The view is not a copy: if the owner changes c, readers of the view see the change immediately.
Library declarations
Java
// java.util.Collections
public static <T> Collection<T> unmodifiableCollection(Collection<? extends T> c)
Parameters
Parameter
Description
c
The collection to expose read-only. Must not be null.
Return Value
Return Value
Description
Collection<T>
A read-only view of c.
Compare with Similar Methods
Pick the wrapper that matches the type you return:
Identity only. A general Collection has no agreed meaning for equals, so this view keeps Object.equals: it is not equal to the list.
Itself. The view is equal only to the very same object.
Use the typed wrapper.unmodifiableList follows List.equals, so it compares element by element and returns true.
Frequently Asked Questions
It returns a read-only view of a Collection. Reading works; any change throws UnsupportedOperationException.
No. It is a view, so changes made to the original collection show through it.
unmodifiableCollection does not pass equals and hashCode to the backing collection; it uses object identity. Use unmodifiableList or unmodifiableSet when equality matters.
When the backing object is not a List, Set, or Map, for example a Deque or PriorityQueue, or when you only want to promise a general Collection.
Wrap a copy: Collections.unmodifiableCollection(new ArrayList<>(c)). Nobody else holds a reference to that copy.