Java Collection Tutorial - Java Collections .unmodifiableSet ( Set <? extends T> s)








Syntax

Collections.unmodifiableSet(Set <? extends T> s) has the following syntax.

public static <T> Set <T> unmodifiableSet(Set <? extends T> s)

Example

In the following code shows how to use Collections.unmodifiableSet(Set <? extends T> s) method.

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
/* w ww  .j a  v a  2  s  . c om*/
public class Main {
   public static void main(String[] args) {
      // create array list
      Set<Character>  set = new HashSet<Character> ();
      
      // populate the list
      set.add('X');
      set.add('Y');
      
      System.out.println("Initial list: "+ set);
      
      // make the list unmodifiable
      Set<Character>  immutableSet= Collections.unmodifiableSet(set);
      
      // try to modify the list
      immutableSet.add('Z');      
   }
}

The code above generates the following result.