概念
参考页面:https://blog.csdn.net/u014727260/article/details/55003402
1.浅拷贝是按位拷贝对象,它会创建一个新对象,这个对象有着原始对象属性值的一份精确拷贝。如果属性是基本类型,拷贝的就是基本类型的值;如果属性是内存地址(引用类型),拷贝的就是内存地址 ,因此如果其中一个对象改变了这个地址,就会影响到另一个对象。
2.深拷贝会拷贝所有的属性,并拷贝属性指向的动态分配的内存。当对象和它所引用的对象一起拷贝时即发生深拷贝。深拷贝相比于浅拷贝速度较慢并且花销较大。
图片参考:https://www.2cto.com/kf/201401/273852.html
实现
拿Map举例:
参考页面:https://www.dutycode.com/map_kaobei_shenkaobei_qiankaobei.html
https://cloud.tencent.com/developer/ask/192566
lambda 要Java8以上版本
@SuppressWarnings("unchecked")
/*
* 序列化实现的方式
*/
public static <T> Map deepClone(Map obj){
T clonedObj = null;
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(obj);
oos.close();
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bais);
clonedObj = (T) ois.readObject();
ois.close();
}catch (Exception e){
e.printStackTrace();
}
return (Map) clonedObj;
}
public static void main(String[] args) {
Map<String, Object> map = new HashMap<>();
map.put("userId", "111");
map.put("userName", "testName");
map.put("isParent", false);
List testList = new ArrayList();
testList.add("test1");
testList.add("test2");
map.put("testList", testList);
//浅拷贝
Map shallowMap1 = map;
//深拷贝 引用类型
Map shallowMap2 = new HashMap<>();
shallowMap2.putAll(map);
//深拷贝 引用类型
Map shallowMap3 = map.entrySet().stream()
.collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue()));
//深拷贝
Map deepCopyMap = deepClone(map);
map.put("userName","testName-edit");
testList.add("test3");
System.out.println("shallowMap1 ="+ shallowMap1.toString());
System.out.println("shallowMap2 ="+ shallowMap2.toString());
System.out.println("shallowMap3 ="+ shallowMap3.toString());
System.out.println("deepCopyMap ="+ deepCopyMap.toString());
}
输出:
shallowMap1 ={testList=[test1, test2, test3], isParent=false, userName=testName-edit, userId=111}
shallowMap2 ={testList=[test1, test2, test3], isParent=false, userName=testName, userId=111}
shallowMap3 ={testList=[test1, test2, test3], isParent=false, userName=testName, userId=111}
deepCopyMap ={testList=[test1, test2], isParent=false, userName=testName, userId=111}