Java Collections checkedList()方法及示例
集合类的 checkedList() 方法存在于java.util包中,用于返回指定列表的动态类型安全视图。这里需要注意的关键是,如果指定的列表是可序列化的,那么返回的列表将是可序列化的。因为null被认为是任何引用类型的值,所以只要支持列表,返回的列表就允许插入null元素。
提示: 该方法与java 1.5及以后的版本兼容。
语法
public static List
checkedList(List list, Class type)
参数: 该方法需要以下参数。
- 要返回的动态类型安全视图的列表
- 该列表允许容纳的元素类型
返回类型: 一个指定列表的动态 类型安全视图
异常 :该方法会抛出 ClassCastException
例子 1 :
// Java program to Demonstrate checkedList() method
// of Collections class for a string value
// Importing required classes
import java.util.*;
// Main class
public class GFG {
// Main driver method
public static void main(String[] argv) throws Exception
{
// Try block to check for exceptions
try {
// Creating an ArrayList of string type by
// declaring object of List
List<String> arlst = new ArrayList<String>();
// Adding element to ArrayList
// by using standard add() method
// Custom input elements
arlst.add("A");
arlst.add("B");
arlst.add("C");
arlst.add("TajMahal");
// Printing the above elements inside ArrayList
System.out.println("List: " + arlst);
// Creating typesafe view of the specified list
// and applying checkedList
List<String> tslst = Collections.checkedList(
arlst, String.class);
// Printing the updated elements of ArrayList
// after applying above operation
System.out.println("Typesafe view of List: "
+ tslst);
}
// Catch block to handle the exceptions
catch (IllegalArgumentException e) {
// Display message on console if exception
// occurs
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
// of Collections class for a string value
// Importing required classes
import java.util.*;
// Main class
public class GFG {
// Main driver method
public static void main(String[] argv) throws Exception
{
// Try block to check for exceptions
try {
// Creating an empty ArrayList of integer type
// by creating an object of List
List<Integer> arlst = new ArrayList<Integer>();
// Adding element to above ArrayList
// by using add() method
arlst.add(20);
arlst.add(30);
arlst.add(40);
arlst.add(50);
// Printing the elements of above ArrayList
System.out.println("List: " + arlst);
// Creating typesafe view of the specified list
// with usage of checkedList() method
List<Integer> tslst = Collections.checkedList(
arlst, Integer.class);
// Printing the elements of ArrayList
// after performing above operation
System.out.println("Typesafe view of List: "
+ tslst);
}
// Catch block to handle the exceptions
catch (IllegalArgumentException e) {
// Display message if exception occurs
System.out.println("Exception thrown : " + e);
}
}
}
输出
List: [20, 30, 40, 50]
Typesafe view of List: [20, 30, 40, 50]