Java Collections checkedList() 方法

2025 年 3 月 21 日 | 阅读 2 分钟

checkedList() 是 Java Collections 类的一个方法,它返回指定列表的动态类型安全视图。如果插入了错误类型的元素,将导致立即发生 ClassCastException。

语法

以下是 checkedList() 方法的声明

参数

参数描述必需/可选
list这是要为其返回动态类型安全视图的列表。必需
type这是列表允许包含的元素的类型。必需

返回值

checkedList() 方法返回指定列表的动态类型安全视图。

异常

ClassCastException

兼容版本

Java 1.5 及以上版本

示例 1

输出

Type safe view of the List is: [A, B, C, D]

示例 2

输出

Checked list content: [one, two, three, four]
Exception in thread "main" java.lang.ClassCastException: Attempt to insert class java.lang.Integer element into collection with element type class java.lang.String
	at java.base/java.util.Collections$CheckedCollection.typeCheck(Collections.java:3038)
	at java.base/java.util.Collections$CheckedCollection.add(Collections.java:3081)
	at myPackage.CollectionCheckedListExample2.main(CollectionCheckedListExample2.java:15)

示例 3

输出

Type safe view of the List is: [10, 20, 30, 40]

示例 4

输出

[RAJ]
[RAJ, 2]