Unmodifiable Set in Java

In this post, we will discuss various methods to create 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. Java Collections – Collections.unmodifiableSet()

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 back in the unmodifiable set.

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

Java

Download   Run Code

Output:

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

2. Java Collections – Collections.unmodifiableCollection()

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.

Java

Download   Run Code

Output:

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

3. Apache Commons Collections – SetUtils.unmodifiableSet()

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 modify 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 unmodifiableSortedSet(SortedSet s) method that returns an unmodifiable sorted set backed by the given sorted set.

Java

Download

Output:

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

 
Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz