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


Java Collections unmodifiableList()用法及代碼示例


java.util.Collections類的unmodifiableList()方法用於返回指定列表的不可修改視圖。此方法允許模塊為用戶提供對內部列表的隻讀訪問權限。對返回列表“read through”的查詢操作到指定列表,並嘗試直接或通過其迭代器修改返回列表,將導致UnsupportedOperationException。

如果指定的列表是可序列化的,則返回的列表將是可序列化的。同樣,如果指定的列表返回列表,則將實現RandomAccess。

用法:


public static <T> ListT> 
    unmodifiableList(List<? extends T> list)

參數:此方法將列表作為要返回其不可修改視圖的參數。

返回值:此方法返回指定列表的不可修改視圖。

以下示例說明了unmodifiableList()方法

示例1:

// Java program to demonstrate 
// unmodifiableList() method 
  
import java.util.*; 
  
public class GFG1 { 
    public static void main(String[] argv) 
        throws Exception 
    { 
        try { 
  
            // creating object of ArrayList<Character> 
            List<Character> list = new ArrayList<Character>(); 
  
            // populate the list 
            list.add('X'); 
            list.add('Y'); 
  
            // printing the list 
            System.out.println("Initial list: " + list); 
  
            // getting unmodifiable list 
            // using unmodifiableList() method 
            List<Character> immutablelist = Collections 
                                                .unmodifiableList(list); 
  
            // printing the list 
            System.out.println("Unmodifiable list: "
                               + immutablelist); 
        } 
  
        catch (UnsupportedOperationException e) { 
            System.out.println("Exception thrown : " + e); 
        } 
    } 
}
輸出:
Initial list: [X, Y]
Unmodifiable list: [X, Y]

示例2:對於UnsupportedOperationException

// Java program to demonstrate 
// unmodifiableList() method 
  
import java.util.*; 
  
public class GFG1 { 
    public static void main(String[] argv) 
        throws Exception 
    { 
        try { 
  
            // creating object of ArrayList<Character> 
            List<Character> list = new ArrayList<Character>(); 
  
            // populate the list 
            list.add('X'); 
            list.add('Y'); 
  
            // printing the list 
            System.out.println("Initial list: " + list); 
  
            // getting unmodifiable list 
            // using unmodifiableList() method 
            List<Character> immutablelist = Collections 
                                                .unmodifiableList(list); 
  
            // Adding element to new Collection 
            System.out.println("\nTrying to modify"
                               + " the unmodifiablelist"); 
            immutablelist.add('Z'); 
        } 
  
        catch (UnsupportedOperationException e) { 
            System.out.println("Exception thrown : " + e); 
        } 
    } 
}
輸出:
Initial list: [X, Y]

Trying to modify the unmodifiablelist
Exception thrown : java.lang.UnsupportedOperationException


相關用法


注:本文由純淨天空篩選整理自RohitPrasad3大神的英文原創作品 Collections unmodifiableList() method in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。