当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java Collections unmodifiableSet()用法及代码示例


java.util.Collections类的unmodifiableSet()方法用于返回指定集合的​​不可修改视图。此方法允许模块为用户提供对内部集的只读访问权限。对返回的集合“read through”进行查询操作到指定的集合,并尝试直接或通过其迭代器修改返回的集合,将导致UnsupportedOperationException。

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

用法:


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

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

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

以下示例说明了unmodifiableSet()方法

示例1:

// Java program to demonstrate 
// unmodifiableSet() method 
// for <Character> value 
  
import java.util.*; 
  
public class GFG1 { 
    public static void main(String[] argv) throws Exception 
    { 
  
        try { 
  
            // creating object of HashSet<Character> 
            Set<Character> set = new HashSet<Character>(); 
  
            // populate the table 
            set.add('X'); 
            set.add('Y'); 
  
            // make the set unmodifiable 
            Set<Character> 
                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 <Character> value 
  
import java.util.*; 
  
public class GFG1 { 
    public static void main(String[] argv) 
        throws Exception 
    { 
  
        try { 
  
            // creating object of HashSet<Character> 
            Set<Character> set = new HashSet<Character>(); 
  
            // populate the table 
            set.add('X'); 
            set.add('Y'); 
  
            // make the set unmodifiable 
            Set<Character> 
                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


相关用法


注:本文由纯净天空筛选整理自RohitPrasad3大神的英文原创作品 Collections unmodifiableSet() method in Java with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。