Java Map 深拷贝与浅拷贝

概念

参考页面: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}
 

 

  • 6
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zhchyun2008

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值