java.util.Collections.unmodifiableSet() Method


Advertisements


Description

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

Declaration

Following is the declaration for java.util.Collections.unmodifiableSet() method.

public static <T> boolean addAll(Collection<? super T> c, T.. a)

Parameters

s − This is the set for which an unmodifiable view is to be returned.

Return Value

The method call returns an unmodifiable view of the specified set.

Exception

NA

Example

The following example shows the usage of java.util.Collections.unmodifiableSet()

Live Demo
package com.tutorialspoint;

import java.util.*;

public class CollectionsDemo {
   public static void main(String[] s) {
   
      // create set
      Set<String> set = new HashSet<String>();

      // populate the set
      set.add("Welcome");
      set.add("to");
      set.add("TP");

      System.out.println("Initial set value: "+set);

      // create unmodifiable set
      Set unmodset = Collections.unmodifiableSet(set);

      // try to modify the set
      unmodset.add("Hello");
   }
}

Let us compile and run the above program, this will produce the following result.

Initial set value: [to, Welcome, TP]
Exception in thread "main" java.lang.UnsupportedOperationException

java_util_collections.htm

Advertisements
E-Books Store