📜  Java中的集合 unmodifiableList() 方法和示例

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

Java中的集合 unmodifiableList() 方法和示例

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

如果指定的列表是可序列化的,则返回的列表将是可序列化的。同样,如果指定的列表执行,则返回的列表将实现 RandomAccess。

句法:

public static  ListT> 
    unmodifiableList(List 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
            List list = new ArrayList();
  
            // 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 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
            List list = new ArrayList();
  
            // 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 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