如何将内容从以前的hashmap传输到新的hashmap?

时间:2013-08-20 06:17:16

标签: java hashmap

  HashMap<String,Integer> map= new HashMap<String,Integer>();
  map.put("first",1);
  map.put("second",2);
  map.put("third",3);

  HashMap<String,Integer> map2= new HashMap<String,Integer>();
  map2= map.clone();

我的问题是如何将项目从地图转移到map2?我的代码是对的吗?

3 个答案:

答案 0 :(得分:7)

很简单。使用参数化构造函数

  HashMap<String,Integer> map2= new HashMap<String,Integer>(map);

答案 1 :(得分:3)

你可以这样做:

HashMap<String,Integer> map2= new HashMap<String,Integer>();
map2.putAll(map);

HashMap<String,Integer> map2= new HashMap<String,Integer>(map);

请注意,在这两种方法中,键和值不重复,只是由HashMap引用。

答案 2 :(得分:1)

如果您正在查看以前使用复制构造函数的深层复制,则 clone是此HashMap实例的浅表副本:键和值本身未克隆

如果您想要上一张地图的浅拷贝,则可以使用pass the map reference to your new map constructor而不是clone方法。

HashMap<String,Integer> map2= new HashMap<>(map);

克隆方法找到SO时有烦恼。

Josh Bloch on Design - Copy Constructor versus Cloning

  

如果您已经阅读了我的书中有关克隆的项目,特别是如果您   在线之间阅读,你会知道我认为克隆是深刻的   破碎。 [...] Cloneable被打破是一种耻辱,但它确实发生了。