java HashMap赋值给另一个HashMap时,当调用方法时,两个Map的值都会改变
Map<String,Integer> a=new HashMap<>();
a.put("a",1);
a.put("b",2);
System.out.println(a);
Map<String,Integer> b=new HashMap<>();
b=a;
System.out.println(b);
b.put("c",3);
System.out.println(a);
System.out.println(b);
结果:

方法一:.putAll()方法
HashMap<String,Integer> a=new HashMap<>();
a.put("a",1);
a.put("b",2);
System.out.println(a);
HashMap<String,Integer> b=new HashMap<>();
b.putAll(a); //放入b中
System.out.println(b);
b.put("c",3);
System.out.prin

本文探讨了在Java中如何正确赋值HashMap,详细分析了使用.putAll()、clone()方法以及遍历赋值时,两个HashMap之间的关系。重点解释了浅拷贝和深拷贝的区别,指出当涉及引用类型时,浅拷贝会导致两个Map同步变化,而深拷贝则能保持独立性。
最低0.47元/天 解锁文章
3973

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



