2013-08-20 50 views

回答

7

据simple.Use参数化构造

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

哇,不知道可能是那么短。谢谢 – ThisGuy

+2

在完美的世界中,Map map2 = ...' - 最好尽可能使用接口。 –

3

你可以这样做:

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

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

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

1

如果您正在寻找以前的地图使用拷贝构造函数深拷贝克隆此HashMap实例的浅表副本:键和值本身不被复制

如果你希望你的前一个地图的浅拷贝你可以使用pass the map reference to your new map constructor而非clone方法。

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

有烦恼过clone方法找到SO

Josh Bloch on Design - Copy Constructor versus Cloning

如果你读过关于我的书克隆的项目,特别是如果你 字里行间,你会知道,我认为克隆是深深 坏了。 [...] Cloneable被破坏是一种遗憾,但它却发生了。