在一些情况下 如果不进行深拷贝而是直接将一个值赋值给另一个变量 如果我们期望这两个变量相互不影响 那么实际情况可能往往出乎我们的意料
public class TestEasy {
public static void main(String[] args) {
//1.基本类型不需要深度拷贝
Map<String, String> map11 = new HashMap<>();
map11.put("test", "1111");
Map<String, String> map22 = new HashMap<>();
map22.putAll(map11);
map22.put("test", "1234");
System.out.println(map11);
System.out.println(map22);
System.out.println("");
//2.非基本类型需要深度拷贝 比如Set<String>
//不深度拷贝
Map<String, Set<String>> map = new HashMap<String, Set<String>>();
Set<String> set = new HashSet<>();
set.add("aaaa");
map.put("1", set);
Map<String, Set<String>> map2 = new HashMap<>();
map2.putAll(map);
Set<String> set2;
set2 = map2.get("1");
set2.add("bbb");
//map和map2实际还是指向同一个map 输出一样的内容
System.out.println(map2.values());
System.out.println(map.values());
System.out.println("");
//深度拷贝
Map<String, Set<String>> mapDeep = new HashMap<String, Set<String>>();
Set<String> setDeep = new HashSet<>();
setDeep.add("aaaa");
mapDeep.put("1", setDeep);
Map<String, Set<String>> map2Deep = new HashMap<>();
map2Deep = deepCopy(mapDeep);
Set<String> set2Deep;
set2Deep = map2Deep.get("1");
set2Deep.add("bbb");
//进行深拷贝后 内容不同了
System.out.println(mapDeep.values());
System.out.println(map2Deep.values());
System.out.println("");
//3.非基本类型需要深度拷贝 比如User
//不深度拷贝
Map<String, User> uMap = new HashMap<>();
User user = new User("zhangsan", 12);
uMap.put("1", user);
Map<String, User> uMap2 = new HashMap<>();
uMap2.putAll(uMap);
User tempUser = uMap2.get("1");
tempUser.setName("abc");
System.out.println(uMap);
System.out.println(uMap2);
System.out.println("");
//深度拷贝
Map<String, User> uMapDeep = new HashMap<>();
User userDeep = new User("zhangsan", 12);
uMapDeep.put("1", userDeep);
Map<String, User> uMap2Deep;
uMap2Deep = deepCopyUser(uMapDeep);
User tempUserDeep = uMap2Deep.get("1");
tempUserDeep.setName("sadsa");
System.out.println(uMapDeep);
System.out.println(uMap2Deep);
System.out.println("");
}
static Map<String, Set<String>> deepCopy(
Map<String, Set<String>> original) {
HashMap<String, Set<String>> copy = new HashMap<>();
for (Map.Entry<String, Set<String>> entry : original.entrySet()) {
copy.put(entry.getKey(),
new HashSet<String>(entry.getValue()));
}
return copy;
}
static Map<String, User> deepCopyUser(
Map<String, User> original) {
HashMap<String, User> copy = new HashMap<>();
for (Map.Entry<String, User> entry : original.entrySet()) {
copy.put(entry.getKey(),
new User(entry.getValue().getName(),entry.getValue().getAge()));
}
return copy;
}
}
public class User {
private String name;
private int age;
User(String name,int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return name + age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
输出
{test=1111}
{test=1234}
[[bbb, aaaa]]
[[bbb, aaaa]]
[[aaaa]]
[[bbb, aaaa]]
{1=abc12}
{1=abc12}
{1=zhangsan12}
{1=sadsa12}