如何使 ArrayList 在Java中只读
给定一个 ArrayList,任务是使这个 ArrayList 在Java中只读。
例子:
Input: ArrayList: [1, 2, 3, 4, 5]
Output: Read-only ArrayList: [1, 2, 3, 4, 5]
Input: ArrayList: [geeks, for, geeks]
Output: Read-only ArrayList: [geeks, for, geeks]
借助 Collections.unmodifiableList() 方法,可以轻松地将 ArrayList 设为只读。该方法以可修改的ArrayList为参数,返回该ArrayList的只读不可修改视图。
句法:
readOnlyArrayList = Collections.unmodifiableList(ArrayList);
下面是上述方法的实现:
// 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');
list.add('Z');
// printing the list
System.out.println("Initial list: "
+ list);
// getting readonly list
// using unmodifiableList() method
List
immutablelist = Collections
.unmodifiableList(list);
// printing the list
System.out.println("ReadOnly ArrayList: "
+ immutablelist);
// Adding element to new Collection
System.out.println("\nTrying to modify"
+ " the ReadOnly ArrayList.");
immutablelist.add('A');
}
catch (UnsupportedOperationException e) {
System.out.println("Exception thrown : " + e);
}
}
}
输出:
Initial list: [X, Y, Z]
ReadOnly ArrayList: [X, Y, Z]
Trying to modify the ReadOnly ArrayList.
Exception thrown : java.lang.UnsupportedOperationException