我有这个代码:
Map<String, Map<String,String>> map = new HashMap<String, Map<String,String>> ();
我想克隆这张 map ,我喜欢这样:
Map<String, Map<String, String>> newMap = (Map<String, Map<String, String>>) ((HashMap<String, Map<String,String>>) map).clone();
然后:
System.out.println(map.get("myKey1").get("myKey2"));
newMap.get("myKey1").put("myKey2","testValue");
System.out.println(map.get("myKey1").get("myKey2"));
System.out.println(newMap.get("myKey1").get("myKey2"));
我得到这个输出:
map.get("myKey1").get("myKey2")
:OldValue
map.get("myKey1").get("myKey2")
: testValue
newMap.get("myKey1").get("myKey2")
: testValue
获取map.get("myKey1").get("myKey2") = testValue
时很奇怪!
最佳答案
https://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html#clone()
Returns a shallow copy of this HashMap instance: the keys and values themselves are not cloned.
答案:您必须遍历要复制和克隆单个元素的任何类型的集合。
建议:如果您想创建某种自动化,请考虑使用序列化,Java 本身不支持对象克隆。
http://www.avajava.com/tutorials/lessons/how-do-i-perform-a-deep-clone-using-serializable.html
这种类型的复制称为深度克隆。
关于java克隆一个包含嵌套映射的映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37593627/