Home » Java Collections unmodifiableSet() Method with Examples

Java Collections unmodifiableSet() Method with Examples

by Online Tutorials Library

Java Collections unmodifiableSet() Method

The unmodifiableSet() method of Java Collections class is used to get an unmodifiable view of the specified set.

Syntax

Following is the declaration of unmodifiableSet() method:

Parameter

Parameter Description Required/Optional
s It is the set for which an unmodifiable view is to be returned. Required

Returns

The unmodifiableSet() method returns an unmodifiable view of the specified set.

Exceptions

NA

Example 1

Test it Now

Output:

Initial Set: [1, 2, 3, 4, 5]  Unmodifiable Set: [1, 2, 3, 4, 5]  Unmodifiable Set: [1, 2, 3, 4, 5, 15]  

Example 2

Test it Now

Output:

Initial Set: [Facebook, Google, Instagram]  Unmodifiable Set: [Facebook, Google, Instagram]  Unmodifiable Set: [Facebook, Google, Instagram, Twitter]  

Example 3

Test it Now

Output:

Original Set: [11, 13, 17]  Exception in thread "main" java.lang.UnsupportedOperationException  at java.base/java.util.Collections$UnmodifiableCollection.add(Collections.java:1056)  at myPackage.CollectionsUnmodifiableSetExample3.main(CollectionsUnmodifiableSetExample3.java:9)  

You may also like