java.util.Collections类的checkedList()方法用于返回指定列表的动态类型安全视图。
如果指定的列表是可序列化的,则返回的列表将是可序列化的。
由于将null视为任何引用类型的值,因此只要后备列表允许,返回的列表就允许插入null元素。
用法:
public static List
checkedList(List list, Class type)
参数:此方法将以下参数作为参数:
list –要为其返回动态类型安全视图的列表
type –列表可以容纳的元素的类型
返回值:此方法返回指定列表的动态类型安全视图
以下示例说明了checkedList()方法
示例1:
// Java program to demonstrate
// checkedList() method
// for String value
import java.util.*;
public class GFG1 {
public static void main(String[] argv) throws Exception
{
try {
// creating object of List
List arlst = new ArrayList();
// Adding element to arlst
arlst.add("A");
arlst.add("B");
arlst.add("C");
arlst.add("TajMahal");
// printing the arrlist
System.out.println("List: " + arlst);
// create typesafe view of the specified list
List
tslst = Collections
.checkedList(arlst, String.class);
// printing the arrlist after operation
System.out.println("Typesafe view of List: " + tslst);
}
catch (IllegalArgumentException e) {
System.out.println("Exception thrown : " + e);
}
}
}
输出:
List: [A, B, C, TajMahal]
Typesafe view of List: [A, B, C, TajMahal]
示例2:
// Java program to demonstrate
// checkedList() method
// for Integer value
import java.util.*;
public class GFG1 {
public static void main(String[] argv) throws Exception
{
try {
// creating object of List
List arlst = new ArrayList();
// Adding element to arlst
arlst.add(20);
arlst.add(30);
arlst.add(40);
arlst.add(50);
// printing the arrlist
System.out.println("List: " + arlst);
// create typesafe view of the specified list
List
tslst = Collections
.checkedList(arlst, Integer.class);
// printing the arrlist after operation
System.out.println("Typesafe view of List: " + tslst);
}
catch (IllegalArgumentException e) {
System.out.println("Exception thrown : " + e);
}
}
}
输出:
List: [20, 30, 40, 50]
Typesafe view of List: [20, 30, 40, 50]