【发布时间】:2015-05-12 21:37:36
【问题描述】:
在 hashmap 中使用 clone():
HashMap<Integer, String> map = new HashMap<>();
map.put(1, "Raj");
map.put(3, "Kumar");
map.put(2, "Ram");
HashMap map1 = (HashMap) map.clone();
map1.put(7, "Kavin");
System.out.println("Map1: "+map1);
System.out.println("Map: "+map);
这将给出输出,
地图 1:{1=Raj, 2=Ram, 3=Kumar, 7=Kavin}
地图:{1=Raj, 2=Ram, 3=Kumar}
但如果我尝试在 jdk8 中运行,则会引发编译错误。
注意:HelloWorld.java 使用未经检查或不安全的操作。
注意:使用 -Xlint 重新编译:详细信息未选中。
方案 2:
HashMap<String, Integer> map = new HashMap<String, Integer>();
map.put("Java", 8);
map.put("Csharp", 5);
Map<String, Integer> mapClone = (Map<String, Integer>)
Collections.checkedMap((Map<String, Integer>)map.clone(), String.class, Integer.class);
但如果我尝试在 jdk8 中运行,则会引发编译错误。
注意:HelloWorld.java 使用未经检查或不安全的操作。
注意:使用 -Xlint 重新编译:详细信息未选中。
为什么??...
【问题讨论】:
-
我看不到编译错误。
-
这些是编译器警告。您的程序已成功编译。
-
这只是一个警告。
-
另外,编译器还为您提供了准确的选项,可用来回答您的为什么问题。