Unmodifiable SortedSet in Java

In this tutorial, we will learn about Unmodifiable SortedSet in Java.

Collections Framework in Java provides a simple way to create unmodifiable lists, sets and maps from existing ones, using the methods in Collections class. Collections class in Java provides unmodifiableSortedSet() method to get an unmodifiable SortedSet from any specified SortedSet. This method returns an unmodifiable view of the specified sets. It allows modules to provide users with “read-only” access to internal sets. Any attempts to modify the returned set, whether direct or via its iterator will result in an UnsupportedOperationException. The returned set will be serializable if the specified set is serializable.

The syntax of unmodifiableSet() method:

Parameters:
set – the sortedset for which an unmodifiable SortedSet is to be returned.

Returns:
an unmodifiable SortedSet of the specified SortedSet.

Example:

Output:

In the above program, we have used unmodifiableSortedSet() method from Collections class to get an unmodifiable SortedSet from TreeSet.

Now let’s see what if we try to modify the unmodifiable SortedSet in Java. As mentioned at the start of this tutorial, it will throw UnsupportedOperationException if we modify the unmodifiable SortedSet, let’s see this with an example.

UnsupportedOperationException on modifying the unmodifiable SortedSet:

Output:

In the above program, we tried to modify unmodifiable SortedSet sortedSet1 by adding 2 values in it. It has thrown UnsupportedOperationException, which clearly indicates that the SortedSet is unmodifiable and will throw exception on attempt to modify it.

Related posts

Leave a Comment