Java 中 Collections checkedSortedMap() 方法的示例
java.util.Collections 类中的 checkedSortedMap() 方法用于返回指定排序映射的动态类型安全视图。
如果指定的映射是可序列化的,则返回的映射将是可序列化的。
由于 null 被认为是任何引用类型的值,因此当后端映射允许插入 null 键或值时,返回的映射允许插入 null 键或值。
语法:
public static SortedMap
checkedSortedMap(SortedMap m, Class keyType, Class valueType)
参数: 该方法接受以下参数
- m – 返回动态类型安全视图的映射
- keyType – 映射允许保存的键的类型
- valueType – 映射允许保存的值的类型
返回值: 该方法返回指定映射的动态 类型安全视图 。
下面是说明 checkedSortedMap()方法的示例
示例 1:
// Java program to demonstrate
// checkedSortedMap() method
// for <String, String> type
import java.util.*;
public class GFG1 {
public static void main(String[] argv)
throws Exception
{
try {
// creating object of SortedMap<String, String>
SortedMap<String, String>
smap = new TreeMap<String, String>();
// Adding element to smap
smap.put("Ram", "Gopal");
smap.put("Karan", "Arjun");
smap.put("Karn", "Veer");
// printing the sorted map
System.out.println("Sorted map:\n"
+ smap);
// create typesafe view of the specified map
SortedMap<String, String>
tsmap = Collections
.checkedSortedMap(smap,
String.class,
String.class);
// printing the typesafe view of specified sorted map
System.out.println("Typesafe view of sorted map:\n"
+ tsmap);
}
catch (IllegalArgumentException e) {
System.out.println("Exception thrown : " + e);
}
}
}
输出:
Sorted map:
{Karan=Arjun, Karn=Veer, Ram=Gopal}
Typesafe view of sorted map:
{Karan=Arjun, Karn=Veer, Ram=Gopal}
示例 2:
// Java程序,演示使用checkedSortedMap()方法,针对<String, Integer>类型
import java.util.*;
public class GFG1 {
public static void main(String[] argv) throws Exception
{
try {
// 创建SortedMap<String, Integer>的对象
SortedMap<String, Integer> smap = new TreeMap<String, Integer>();
// 将元素添加到smap中
smap.put("Ram", 20);
smap.put("Karan", 39);
smap.put("Karn", 40);
// 打印排序后的map
System.out.println("排序后的map:\n"
+ smap);
// 创建指定map的类型安全视图
SortedMap<String, Integer>
tsmap = Collections
.checkedSortedMap(smap,
String.class,
Integer.class);
// 打印指定排序map的类型安全视图
System.out.println("排序后的map的类型安全视图:\n"
+ tsmap);
}
catch (IllegalArgumentException e) {
System.out.println("抛出异常 : " + e);
}
}
}
输出结果:
排序后的map:
{Karan=39, Karn=40, Ram=20}
排序后的map的类型安全视图:
{Karan=39, Karn=40, Ram=20}