當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。