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

java之浅拷贝、深拷贝

1、java数据类型

java数据类型分为基本数据类型和引用数据类型
基本数据类型:byte、short、int、long、float、double、boolean、char。
引用类型:常见的有类、接口、数组、枚举等。

2、浅拷贝、深拷贝

以下探讨的浅拷贝、深拷贝是通过Object类中的clone()方法进行的。

Object.javaprotected native Object clone() throws CloneNotSupportedException;

2.1 浅拷贝:引用数据类型只复制引用。
Book.java

public class Book {private String bookName;private int price;getter/settertoString();
}

Persion.java

public class PeoSon implements Cloneable {private int age;private Book book;public PeoSon(int age) {this.age = age;}@Overrideprotected Object clone() throws CloneNotSupportedException {return super.clone();}getter/setter
toString();
}

测试:

Book book = new Book("编译原理", 10);PeoSon p1 = new PeoSon(123);p1.setBook(book);PeoSon p2 = (PeoSon) p1.clone();System.out.println(p1);System.out.println(p2);System.out.println("--------p1更改book的name值后--------");p1.getBook().setBookName("java从入门到入坟"); System.out.println(p1);System.out.println(p2);

打印结果:

PeoSon{age=123, book=Book{bookName=‘编译原理’, price=10}}
PeoSon{age=123, book=Book{bookName=‘编译原理’, price=10}}
--------p1更改book的name值后--------
PeoSon{age=123, book=Book{bookName=‘java从入门到入坟’, price=10}}
PeoSon{age=123, book=Book{bookName=‘java从入门到入坟’, price=10}}

可以看到,只修改了p1中引用对象book的名称,但是p2中引用对象book的名称也发生了变化!
原因: PeoSon p2 = (PeoSon) p1.clone() 是浅拷贝,p1、p2指向同一块堆内存空间。

在这里插入图片描述
修改图书名称后:在这里插入图片描述

上述类PeoSon 类实现Cloneable 接口;使用clone()方法时,必须实现该接口并且复写clone()方法。

public interface Cloneable {
}

Cloneable 只是一个标记性接口,实现这个接口表明要重写clone()。
并且在Object类的clone()方法中也明确说明了:
if the class of this object does not implement the interface Cloneable , then a
CloneNotSupportedException is thrown.

 /*** Creates and returns a copy of this object.  The precise meaning* of "copy" may depend on the class of the object. The general* intent is that, for any object {@code x}, the expression:* <blockquote>* <pre>* x.clone() != x</pre></blockquote>* will be true, and that the expression:* <blockquote>* <pre>* x.clone().getClass() == x.getClass()</pre></blockquote>* will be {@code true}, but these are not absolute requirements.* While it is typically the case that:* <blockquote>* <pre>* x.clone().equals(x)</pre></blockquote>* will be {@code true}, this is not an absolute requirement.* <p>* By convention, the returned object should be obtained by calling* {@code super.clone}.  If a class and all of its superclasses (except* {@code Object}) obey this convention, it will be the case that* {@code x.clone().getClass() == x.getClass()}.* <p>* By convention, the object returned by this method should be independent* of this object (which is being cloned).  To achieve this independence,* it may be necessary to modify one or more fields of the object returned* by {@code super.clone} before returning it.  Typically, this means* copying any mutable objects that comprise the internal "deep structure"* of the object being cloned and replacing the references to these* objects with references to the copies.  If a class contains only* primitive fields or references to immutable objects, then it is usually* the case that no fields in the object returned by {@code super.clone}* need to be modified.* <p>* The method {@code clone} for class {@code Object} performs a* specific cloning operation. First, if the class of this object does* not implement the interface {@code Cloneable}, then a* {@code CloneNotSupportedException} is thrown. Note that all arrays* are considered to implement the interface {@code Cloneable} and that* the return type of the {@code clone} method of an array type {@code T[]}* is {@code T[]} where T is any reference or primitive type.* Otherwise, this method creates a new instance of the class of this* object and initializes all its fields with exactly the contents of* the corresponding fields of this object, as if by assignment; the* contents of the fields are not themselves cloned. Thus, this method* performs a "shallow copy" of this object, not a "deep copy" operation.* <p>* The class {@code Object} does not itself implement the interface* {@code Cloneable}, so calling the {@code clone} method on an object* whose class is {@code Object} will result in throwing an* exception at run time.** @return     a clone of this instance.* @throws  CloneNotSupportedException  if the object's class does not*               support the {@code Cloneable} interface. Subclasses*               that override the {@code clone} method can also*               throw this exception to indicate that an instance cannot*               be cloned.* @see java.lang.Cloneable*/protected native Object clone() throws CloneNotSupportedException;

2.2 深拷贝
Book.java

public class Book implements Cloneable{private String bookName;private int price;@Overrideprotected Object clone() throws CloneNotSupportedException {return super.clone();}public Book(String bookName, int price) {this.bookName = bookName;this.price = price;}
get/set
toString();
}

Person.java

public class PeoSon implements Cloneable {private int age;private Book book;public PeoSon(int age) {this.age = age;}@Overrideprotected Object clone() throws CloneNotSupportedException {PeoSon p = (PeoSon) super.clone();Book clone = (Book) book.clone();p.setBook(clone);return p;}get/set
toString();
}

注意:Book.java、Person.java 都实现了Cloneable接口并且复写了clone()方法。
测试:

  		Book book = new Book("编译原理", 10);PeoSon p1 = new PeoSon(123);p1.setBook(book);PeoSon p2 = (PeoSon) p1.clone();System.out.println(p1);System.out.println(p2);System.out.println("-----p1更改book的name值后-----");p1.getBook().setBookName("java从入门到入坟");System.out.println(p1);System.out.println(p2);

PeoSon{age=123, book=Book{bookName=‘编译原理’, price=10}}
PeoSon{age=123, book=Book{bookName=‘编译原理’, price=10}}
-----p1更改book的name值后-----
PeoSon{age=123, book=Book{bookName=‘java从入门到入坟’, price=10}}
PeoSon{age=123, book=Book{bookName=‘编译原理’, price=10}}

可以看到修改p1中引用数据类型book的bookName属性值后,p2对应属性值不会发生改变。
原因:深拷贝会把所有属性值复制一份,因此改变一个对象的属性值后,其他对象不受影响。
在这里插入图片描述
在这里插入图片描述
在深度拷贝中,需要被拷贝的对象中的所有引用数据类型都实现Cloneable()接口并且重写clone()方法,如果一个对象有好多引用数据类型,则比较费劲,有没有其他方法呢 ? 使用序列化!
序列化是将对象写到流中便于传输,而反序列化则是把对象从流中读取出来。这里写到流中的对象则是原始对象的一个拷贝,因为原始对象还存在 JVM 中,所以我们可以利用对象的序列化产生克隆对象,然后通过反序列化获取这个对象。

注意每个需要序列化的类都要实现 Serializable 接口,如果有某个属性不需要序列化,可以将其声明为 transient,即将其排除在克隆属性之外。

    public Object deepClone() throws Exception {// 序列化ByteArrayOutputStream bos = new ByteArrayOutputStream();ObjectOutputStream oos = new ObjectOutputStream(bos);oos.writeObject(this);// 反序列化ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());ObjectInputStream ois = new ObjectInputStream(bis);return ois.readObject();}

简单使用案例:

public class CC2 implements Serializable {private String color;@Overridepublic String toString() {return "CC2{" +"color='" + color + '\'' +'}';}public CC2(String color) {this.color = color;}public String getColor() {return color;}public void setColor(String color) {this.color = color;}
}
public class BB2 implements Serializable {private String name;private int age;private CC2 c;public BB2() {}public BB2(String name, int age, CC2 c) {this.name = name;this.age = age;this.c = c;}@Overridepublic String toString() {return "BB2{" +"name='" + name + '\'' +", age=" + age +", c=" + c +'}';}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;}public CC2 getC() {return c;}public void setC(CC2 c) {this.c = c;}
}
public class AA2 implements Serializable {private int age;private BB2 b;public AA2(int age, BB2 b) {this.age = age;this.b = b;}@Overridepublic String toString() {return "AA2{" +"age=" + age +", b=" + b +'}';}public Object deepClone() throws Exception {// 序列化ByteArrayOutputStream bos = new ByteArrayOutputStream();ObjectOutputStream oos = new ObjectOutputStream(bos);oos.writeObject(this);// 反序列化ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());ObjectInputStream ois = new ObjectInputStream(bis);return ois.readObject();}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public BB2 getB() {return b;}public void setB(BB2 b) {this.b = b;}
}
public class TT2 {public static void main(String[] args) throws Exception {AA2 aa2 = new AA2(10, new BB2("李四", 20, new CC2("红色")));AA2 o = (AA2) aa2.deepClone();System.out.println(aa2);System.out.println(o);System.out.println("----------------------------------");aa2.getB().setName("新的值");System.out.println(aa2);System.out.println(o);}
}

参考链接

相关文章:

  • 北京网站建设多少钱?
  • 辽宁网页制作哪家好_网站建设
  • 高端品牌网站建设_汉中网站制作
  • vscode和edge浏览器等鼠标输入光标变透明
  • 单链表应用
  • 【Android】UI拓展之滑动菜单、悬浮按钮、CoordinatorLayout布局等
  • excel透视图、看板案例(超详细)
  • 保姆级Maven安装、配置、版本查询教程(包含配置本地仓库、阿里云私服、环境变量)
  • PWM(Pulse-width modulation)脉冲宽度调制
  • 计算机毕业设计PySpark+Scrapy农产品推荐系统 农产品爬虫 农产品商城 农产品大数据 农产品数据分析可视化 PySpark Hadoop
  • Leetcode3243. 新增道路查询后的最短距离 I
  • C#——类与结构
  • MySQL-进阶篇-锁(全局锁、表级锁、行级锁)
  • 两个月冲刺软考——关系模式中的候选关键字与如何分解为无损连接并保持函数依赖的解法(例题讲解,看完必会)
  • 面向对象程序设计原则——里氏替换原则(LSP)
  • 1098 Insertion or Heap Sort
  • 复旦NLP团队新作:大规模语言模型从理论到实践PDF版
  • WHAT - 通过 react-use 源码学习 React(Lifecycles 篇)
  • 《Javascript高级程序设计 (第三版)》第五章 引用类型
  • 4. 路由到控制器 - Laravel从零开始教程
  • Dubbo 整合 Pinpoint 做分布式服务请求跟踪
  • golang 发送GET和POST示例
  • IDEA 插件开发入门教程
  • JS 面试题总结
  • JS学习笔记——闭包
  • PHP变量
  • React的组件模式
  • React中的“虫洞”——Context
  • 笨办法学C 练习34:动态数组
  • 不发不行!Netty集成文字图片聊天室外加TCP/IP软硬件通信
  • 紧急通知:《观止-微软》请在经管柜购买!
  • 聚类分析——Kmeans
  • 判断客户端类型,Android,iOS,PC
  • 浅析微信支付:申请退款、退款回调接口、查询退款
  • 软件开发学习的5大技巧,你知道吗?
  • 微信端页面使用-webkit-box和绝对定位时,元素上移的问题
  • 一些关于Rust在2019年的思考
  • linux 淘宝开源监控工具tsar
  • Redis4.x新特性 -- 萌萌的MEMORY DOCTOR
  • shell使用lftp连接ftp和sftp,并可以指定私钥
  • ​​​​​​​ubuntu16.04 fastreid训练过程
  • ​数据结构之初始二叉树(3)
  • #微信小程序(布局、渲染层基础知识)
  • $redis-setphp_redis Set命令,php操作Redis Set函数介绍
  • (2/2) 为了理解 UWP 的启动流程,我从零开始创建了一个 UWP 程序
  • (免费领源码)Java#Springboot#mysql农产品销售管理系统47627-计算机毕业设计项目选题推荐
  • (十)【Jmeter】线程(Threads(Users))之jp@gc - Stepping Thread Group (deprecated)
  • (十七)devops持续集成开发——使用jenkins流水线pipeline方式发布一个微服务项目
  • (已解决)报错:Could not load the Qt platform plugin “xcb“
  • (转载)跟我一起学习VIM - The Life Changing Editor
  • .net core使用EPPlus设置Excel的页眉和页脚
  • .NET MAUI Sqlite数据库操作(二)异步初始化方法
  • .net 按比例显示图片的缩略图
  • .net 开发怎么实现前后端分离_前后端分离:分离式开发和一体式发布
  • .NET 使用 XPath 来读写 XML 文件
  • .Net程序帮助文档制作
  • .NET教程 - 字符串 编码 正则表达式(String Encoding Regular Express)
  • @DateTimeFormat 和 @JsonFormat 注解详解