📜  Java中的集合 unmodifiableSet() 方法及示例

📅  最后修改于: 2022-05-13 01:58:09.307000             🧑  作者: Mango

Java中的集合 unmodifiableSet() 方法及示例

Java.util.Collections类的unmodifiableSet()方法用于返回指定集合的不可修改视图。这种方法允许模块为用户提供对内部集合的“只读”访问。对返回集“通读”到指定集的查询操作,并尝试修改返回集,无论是直接还是通过其迭代器,都会导致 UnsupportedOperationException。

如果指定的集合是可序列化的,则返回的集合将是可序列化的。

句法:

public static  Set unmodifiableSet(Set s)

参数:此方法将集合作为要为其返回不可修改视图的参数。

返回值:此方法返回指定集合的不可修改视图

以下是说明unmodifiableSet()方法的示例

示例 1:

// Java program to demonstrate
// unmodifiableSet() method
// for  value
  
import java.util.*;
  
public class GFG1 {
    public static void main(String[] argv) throws Exception
    {
  
        try {
  
            // creating object of HashSet
            Set set = new HashSet();
  
            // populate the table
            set.add('X');
            set.add('Y');
  
            // make the set unmodifiable
            Set
                immutableSet = Collections
                                   .unmodifiableSet(set);
  
            // printing unmodifiableSet
            System.out.println("unmodifiable Set: "
                               + immutableSet);
        }
  
        catch (UnsupportedOperationException e) {
            System.out.println("Exception thrown : " + e);
        }
    }
}
输出:
unmodifiable Set: [X, Y]

示例 2:对于UnsupportedOperationException

// Java program to demonstrate
// unmodifiableSet() method
// for  value
  
import java.util.*;
  
public class GFG1 {
    public static void main(String[] argv)
        throws Exception
    {
  
        try {
  
            // creating object of HashSet
            Set set = new HashSet();
  
            // populate the table
            set.add('X');
            set.add('Y');
  
            // make the set unmodifiable
            Set
                immutableSet = Collections
                                   .unmodifiableSet(set);
  
            // printing unmodifiableSet
            System.out.println("unmodifiable Set: "
                               + immutableSet);
  
            System.out.println("\nTrying to modify"
                               + " the unmodifiable set");
            immutableSet.add('Z');
        }
  
        catch (UnsupportedOperationException e) {
            System.out.println("Exception thrown : " + e);
        }
    }
}
输出:
unmodifiable Set: [X, Y]

Trying to modify the unmodifiable set
Exception thrown : java.lang.UnsupportedOperationException