当前位置: 首页 > news >正文

java - 深拷贝 浅拷贝

一.定义

1.浅拷贝

1.定义

浅拷贝只复制对象的引用,不复制引用指向的实际对象。对基本数据类型复制值,对引用类型的值复制其引用。

2.实现方法

通过重写Object类的clone()方法,并让类实现Cloneable接口

3.代码示例
// 浅拷贝
public class Student implements Cloneable{int age;String name;@Overrideprotected Object clone() throws CloneNotSupportedException {return super.clone();}
}

2.深拷贝

1.定义

深拷贝不止复制对象本身,还递归复制对象中所有引用的对象,使新对象和旧对象之间完全独立

2.实现方法

1.让所有嵌套的引用类型也实现 Cloneable 接口并重写 clone(),在顶层对象的 clone() 中递归调用嵌套对象的 clone()

2.通过序列化将对象写入流,再从流中读取,序列化方式简单易用,但性能较低

3.代码示例
1.递归调用
class Address implements Cloneable {String city;public Address(String city) {this.city = city;}@Overrideprotected Object clone() throws CloneNotSupportedException {return super.clone();}
}class Person implements Cloneable {String name;Address addr; public Person(String name, Address addr) {this.name = name;this.addr = addr;}@Overrideprotected Object clone() throws CloneNotSupportedException {Person copy = (Person) super.clone();copy.addr = (Address) this.addr.clone(); return copy;}
}
2.序列化
class Address implements Serializable {String city;public Address(String city) {this.city = city;}
}class Person implements Serializable {String name;Address addr;public Person(String name, Address addr) {this.name = name;this.addr = addr;}Person deepCopy() throws Exception {// 写入字节流ByteArrayOutputStream bos = new ByteArrayOutputStream();ObjectOutputStream oos = new ObjectOutputStream(bos);oos.writeObject(this);// 将字节序列恢复为新对象ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray()));return (Person) ois.readObject();}
}

http://www.lryc.cn/news/612828.html

相关文章:

  • KT148A 语音芯片自研板烧录方案:接口预留与电路连接指南
  • 线上业务突然流量掉 0 ?一次 DNS 污染排查与自救实录
  • itextPdf获取pdf文件宽高不准确
  • 无人机航拍数据集|第8期 无人机海上目标检测YOLO数据集3641张yolov11/yolov8/yolov5可训练
  • BES2700量产项目
  • 7. 什么是事件委托
  • 经营帮:重构企业经营全流程,打造产业互联网新生态
  • 上位机知识篇---AT指令
  • LabVIEW实验室测试框架
  • 复合机器人破局之路:如何逆袭突围
  • 强化学习详解:从理论到前沿的全面解析
  • 知识随记-----Qt 实用技巧:自定义倒计时按钮防止用户频繁点击
  • GitHub 趋势日报 (2025年08月06日)
  • 网络安全与软件定义汽车的发展
  • 【LLM】扩散模型与自回归模型:文本生成的未来对决
  • 分布式事务与分布式锁
  • “物联网+职业本科”:VR虚拟仿真实训室的发展前景
  • USB枚举介绍 以及linux USBFFS应用demo
  • 抖音、快手、视频号等多平台视频解析下载 + 磁力嗅探下载、视频加工(提取音频 / 压缩等)
  • Go语言Ebiten坦克大战
  • JVM类加载
  • Redis中间件(三):Redis存储原理与数据模型
  • Spring MVC拦截器与过滤器的区别详解
  • Ubuntu24.04的“errors from xkbcomp are not fatal to the X server”终极修复方案
  • Ethereum:如何优雅部署 NPM 包中的第三方智能合约?
  • SpringBoot学习日记 Day5:解锁企业级开发核心技能
  • 90-基于Flask的中国博物馆数据可视化分析系统
  • 8- 知识图谱 — 应用案例怎么 “落地” 才有效?构建流程与行业实践全解析
  • LoRaWAN的网络拓扑
  • Kong vs. NGINX:从反向代理到云原生网关的全景对比