【问题标题】:clone() method in hashmaphashmap 中的 clone() 方法
【发布时间】: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 重新编译:详细信息未选中。

为什么??...

【问题讨论】:

  • 我看不到编译错误
  • 这些是编译器警告。您的程序已成功编译。
  • 这只是一个警告。
  • 另外,编译器还为您提供了准确的选项,可用来回答您的为什么问题。

标签: java hashmap clone


【解决方案1】:

注意:HelloWorld.java 使用未经检查或不安全的操作。

注意:使用 -Xlint 重新编译:详细信息未选中。

这些只是警告而不是Compilation Error

这些警告只是意味着编译器无法检查您是否 以类型安全的方式使用集合,使用泛型。

【讨论】:

  • 谢谢...但是,这个警告到底是什么意思??
  • 用-Xlint标志编译你的代码你会得到详细的解释
  • 对不起。怎么编译这样的。?什么是 -Xlint 标志?我对此一无所知...请帮助我..
  • javac -Xlint YourJavaProgram.java ,在你的terminal/cmd中试试这个命令
  • -X 是 Java 命令中各种“扩展选项”的标准前缀。 lint 是一个标准术语,用于生成有关代码中可疑内容的详细警告。阅读上面的Wikipedia 条目。
猜你喜欢
  • 2014-05-19
  • 1970-01-01
  • 2015-07-16
  • 1970-01-01
  • 1970-01-01
  • 2014-12-27
  • 2018-08-16
  • 2018-06-10
  • 2011-07-04
相关资源
最近更新 更多