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


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。