public static void main(String[] args) {
Map<String, Map<String, String>> tempMap=new HashMap<>();
Map<String, String> map=new HashMap<>();
map.put("1","你好");
tempMap.put("1",map);
for (String key : tempMap.keySet()) {
Map<String, String> parentMap = tempMap.get(key);
parentMap.put("2","不好");
}
System.out.println(tempMap.toString());
}
debug:

可以发现map2 赋值给map3的是引用地址所以map3的任何改变都会直接反应到map2上
要使得tempMap里面的值不会因为parentMap的改变而改变,可以在循环中使用clone()方法来创建一个新的parentMap副本,然后对副本进行操作。修改后的代码如下:
public static void main(String[] args) {
Map<String, Map<String, String>> tempMap=new HashMap<>();
Map<String, String> map=new HashMap<>();
Map<String, String> parentMap=new HashMap<>();
map.put("1","你好");
tempMap.put("1",map);
for (String key : tempMap.keySet()) {
// parentMap = tempMap.get(key);
parentMap = new HashMap<>(tempMap.get(key));// 使用clone()方法创建副本
parentMap.put("2","不好");
}
System.out.println(tempMap.toString());
}

这样,对parentMap的改变就不会影响到tempMap里面的值。
Java编程:如何避免Map子映射修改影响父映射
文章讲述了在Java中,如何通过使用`clone()`方法创建Map的副本来防止父映射(如tempMap)中的值因子映射(如parentMap)修改而变化。通过示例代码展示了这一技巧的应用。
1224

被折叠的 条评论
为什么被折叠?



