Java中的checkedCollection()方法及示例
java.util.Collections类中的 checkedCollection() 方法用于返回指定集合的动态类型安全视图。返回的集合不会将hashCode和equals操作传递到支持集合,而是依赖于Object的equals和hashCode方法。这是为了在支持集合是set或list的情况下保留这些操作的契约。如果指定的集合是可序列化的,则返回的集合将是可序列化的。
由于null被认为是任何引用类型的值,因此返回的集合允许在支持集合允许时插入空元素。
语法:
public static Collection checkedCollection(Collection c, Class type)
参数: 该方法需要两个参数
- 要返回动态类型安全视图的集合
- c可以持有的元素类型
返回类型: 这个方法返回指定集合的动态类型安全视图。
示例1:
// Java program to demonstrate
// checkedCollection() method
// for String value
// Importing utility 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 by
// creating object of List of string type
List<String> arlst = new ArrayList<String>();
// Adding element to arrlist
// using add() method
// Custom input elements
arlst.add("CSS");
arlst.add("PHP");
arlst.add("HTML");
arlst.add("TajMahal");
// Printing the ArrayList
System.out.println("List: " + arlst);
// Now create typesafe view of the collection by
// creating object of Collection class of string
// type
Collection<String> tslst
= Collections.checkedCollection(
arlst, String.class);
// Printing the updated ArrayList
// after applying checkedCollection() method
System.out.println("Typesafe view of List: "
+ tslst);
}
// Catch block to handle the exceptions
catch (IllegalArgumentException e) {
// Print message to be displayed on console
// when exception occurs
System.out.println("Exception thrown : " + e);
}
}
}
输出:
List: [CSS, PHP, HTML, TajMahal]
Typesafe view of List: [CSS, PHP, HTML, TajMahal]
示例2:
// Java程序演示Collection类的checkedCollection()方法
// 以Integer类型为示例
// 导入类
import java.util.*;
// 主类
public class GFG {
// 主方法
public static void main(String[] argv) throws Exception
{
// 检查异常的try块
try {
// 通过声明List类型的对象创建一个空的整数ArrayList
List<Integer> arlst = new ArrayList<Integer>();
// 使用add()方法将元素添加到ArrayList中
arlst.add(20);
arlst.add(30);
arlst.add(40);
arlst.add(50);
// 打印上面的ArrayList
System.out.println("List: " + arlst);
// 现在使用checkedCollection()方法创建类型安全的视图
Collection<Integer> tslst
= Collections.checkedCollection(
arlst, Integer.class);
// 在上述操作之后打印更新的ArrayList
System.out.println("Typesafe view of List: "
+ tslst);
}
// 处理异常的catch块
catch (IllegalArgumentException e) {
// 如果异常发生时,则显示消息
System.out.println("Exception thrown : " + e);
}
}
}
输出:
List: [20, 30, 40, 50]
Typesafe view of List: [20, 30, 40, 50]
极客教程