This post will discuss various methods to create an unmodifiable set in Java.

Unmodifiable sets are “read-only” wrappers over other collections. They do not support any modification operations such as add, remove, and clear, but their underlying collection can be changed. Sets that additionally guarantee that no change in the Collection object will ever be visible are referred to as immutable.

It is worth noting that making a set final will not make it unmodifiable. We can still add elements or remove elements from it. Only the reference to the set is final.

1. Using Collections.unmodifiableSet() method

Collections unmodifiableSet(Set s) returns an unmodifiable “read-only” view of the specified set. Any attempt to modify the returned set directly or using an iterator will result in an UnsupportedOperationException. However, any changes made to the original set will be reflected in the unmodifiable set.

Please note that Collections also provides an unmodifiableSortedSet(SortedSet s) method that returns an unmodifiable view of the specified sorted set.

Download  Run Code

Output:

java.lang.UnsupportedOperationException
[Java, C++, Go]

2. Using Collections.unmodifiableCollection() method

Collection interface offers another method, unmodifiableCollection(Set s), which returns an unmodifiable view of the specified collection. This is similar to unmodifiableSet() except it returns a Collection instead of a Set.

Download  Run Code

Output:

java.lang.UnsupportedOperationException
[Java, C++, Go]

3. Using Apache Commons Collections

Apache Commons Collections SetUtils class provides unmodifiableSet(Set s) that returns an unmodifiable set backed by the given set. If the given set is null, it throws a NullPointerException. The set will throw an UnsupportedOperationException if any modification operation is performed on it. However, any changes made to the original set will be reflected in the returned set.

Please note that Apache Commons Collections SetUtils class also provides the unmodifiableSortedSet(SortedSet s) method that returns an unmodifiable sorted set backed by the given sorted set.

Download Code

Output:

java.lang.UnsupportedOperationException
[Java, C++, Go]

That’s all about unmodifiable Set in Java.