当前位置: 首页 > 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.dtcms.com/a/320418.html

相关文章:

  • 对比学习(Contrastive Learning)面试基础
  • Python 深入浅出装饰器
  • 2026计算机毕业设计选题推荐:如何通过项目实用性来选择创新且高通过率的课题
  • Dify-16: 开发环境配置
  • 【MySQL】SQL优化
  • Linux Shell为文件添加BOM并自动转换为unix格式
  • C++之队列浅析
  • 每日算法刷题Day58:8.7:leetcode 单调栈5道题,用时2h
  • 零基础-动手学深度学习-9.3. 深度循环神经网络
  • Langchain入门:对话式RAG
  • Tool Learning的基本概念及应用
  • 数据结构——栈、队列
  • python题目练习 无重叠区间
  • Linux学习-数据结构(二叉树)
  • 嵌入式开发学习———Linux环境下IO进程线程学习(六)
  • 了解大型语言模型:力量与潜力
  • SpringBoot学习日记 Day5:解锁企业级开发核心技能
  • PCIe Base Specification解析(九)
  • 多线程的使用
  • 2025 最新 ECharts 下载、安装与配置教程
  • Linux 中断系统全览解析:从硬件到软件的全路线理解
  • Oracle 19C In-Memory 列存储技术测试
  • Qwen系列模型
  • [链表]两两交换链表中的节点
  • 【感知机】感知机(perceptron)学习算法的对偶形式
  • aurora rx没有ready信号
  • 哈希表——指针数组与单向链表的结合
  • linux顽固进程查看并清理
  • Java包装类详解与应用指南
  • SupChains技术团队:需求预测中减少使用分层次预测(五)