Java Collections checkedSortedSet() 方法

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

checkedSortedSet()Java Collections 类的一个内置方法。此方法用于获取指定已排序集合(sorted set)的动态类型安全视图。

语法

以下是 checkedSortedSet() 方法的声明

参数

参数描述必需/可选
s要为其返回动态类型安全视图的已排序集合。必需
types 允许包含的元素类型。必需

返回值

checkedSortedSet() 方法会自动以升序返回指定已排序集合(Sorted Set)的动态类型安全视图。

异常

ClassCastException

兼容版本

Java 1.5 及以上版本

示例 1

输出

Type safe view of the Set is: [Hindi100, TpointTech, JavaTraining, SSSIT]

示例 2

输出

The view of the Sorted Set is: [100, 200, 500, 1100]

示例 3

输出

Dynamic type safe view of Sorted Set is: [800, 1100, 5000]
Exception in thread "main" java.lang.ClassCastException: Attempt to insert class java.lang.String element into collection with element type class java.lang.Integer
	at java.base/java.util.Collections$CheckedCollection.typeCheck(Collections.java:3038)
	at java.base/java.util.Collections$CheckedCollection.add(Collections.java:3081)
	at myPackage.CollectionCheckedSortedSetExample3.main(CollectionCheckedSortedSetExample3.java:12)