java之浅拷贝、深拷贝

news2024/9/19 10:42:23

1、java数据类型

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

2、浅拷贝、深拷贝

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

Object.java

 protected native Object clone() throws CloneNotSupportedException;

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

public class Book {

    private String bookName;
    private int price;
	
	getter/setter
	toString();
}

Persion.java

public class PeoSon implements Cloneable {

    private int age;
    private Book book;

    public PeoSon(int age) {
        this.age = age;

    }
 @Override
    protected 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;
    @Override
    protected 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;

    }

    @Override
    protected 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;

    @Override
    public 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;
    }

    @Override
    public 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;
    }

    @Override
    public 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);

    }
}

参考链接

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2092247.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Python matplotlib绘图 plt.barh 水平条形图调整顺序逆序排列

使用matplotlib 中的 plt.barh 绘制水平条形图时&#xff0c;数据的排列顺序默认由小到大排列&#xff0c;即数据条由短到长排列展示&#xff0c;如果想让数据条由长到短排列展示&#xff0c;可尝试以下代码。 import matplotlib.pyplot as plt import pandas as pd import nu…

MySQL——基础操作

一、数据库的创建 1.1 库的创建 在使用数据库时&#xff0c;最先操作的是创建一个数据库。使用语法如下&#xff1a; CREATE DATABASE [IF NOT EXISTS] database_name [[DEFAULT] CHARSETcharset_name] [[DEFAULT] COLLATEcollation_name]; 对上述语句进行简单说明&#xf…

【秋招笔试题】讨厌冒泡排序

题解&#xff1a;免费的操作是分别在奇偶下标进行排序&#xff0c;收费的操作会改变他们下标的奇偶性&#xff0c;那么直接统计在排序后有多少元素的下标发生变化了即可。 #include <iostream> #include <vector> #include <algorithm> #include "map&…

猫头虎 分享:Python库 XGBoost 的简介、安装、用法详解入门教程

猫头虎 分享&#xff1a;Python库 XGBoost 的简介、安装、用法详解入门教程 &#x1f3af; ✨ 引言 今天猫头虎收到一位粉丝的提问&#xff1a;“猫哥&#xff0c;我在项目中需要用到 XGBoost&#xff0c;可是对它的了解不够深入&#xff0c;不知道从哪开始&#xff0c;能否详…

线性查找表的应用:用户登录注册程序

线性查找表是很简单的数据结构和算法。网站的用户登录注册时是基本的功能。本文首先给出线性查找表的基本实现&#xff0c;然后给出在用户登录注册的程序流程图&#xff0c;并将线性查找表应用到用户查询这一具体任务&#xff0c;并基于 Python 语言在控制台实现用户注册、登录…

ComfyUI使用Flux模型

ComfyUI是一个强大的用户界面&#xff0c;支持多种图像处理和生成模型&#xff0c;而Flux是一系列由Black Forest Labs开发的扩散模型。 准备工作 1. 下载所需文件 下载地址&#xff1a; comfyanonymous/flux_text_encoders at main (hf-mirror.com)https://hf-mirror.com/…

django企业开发实战-学习小结

写在前面 初次阅读此书是三年前&#xff0c;当时没经历过完整的项目 觉得这书就是扯淡 后来经历过项目加班与毒打 今天再翻开此书 觉得实乃不可多得之物 花些时间啃下来吧 需求 需求文档 写文档&#xff0c;列举需要实现的功能&#xff0c;详细列举&#xff0c;不考虑技术实…

Leetcode Hot 100刷题记录 -Day6(滑动窗口)

无重复字符的最长子串 问题描述&#xff1a; 给定一个字符串 s &#xff0c;请你找出其中不含有重复字符的 最长子串的长度。 示例 1: 输入: s "abcabcbb" 输出: 3 解释: 因为无重复字符的最长子串是 "abc"&#xff0c;所以其长度为 3。示例 2: 输入: s …

10:Logic软件原理图中添加电源与GND

Logic软件原理图中添加电源与GND

“品牌VS套路:华为、格行、中兴随身WiFi谁才是真良心?“

咱们打工人月末有三光&#xff0c;工资花光&#xff0c;流量用光&#xff0c;话费剩光光。 不过除了工资没办法解决&#xff0c;剩下两个还能抢救一下 提起这个事情的起因是我发现现在的互联网平台到处都是推销随身WiFi的&#xff0c;什么零月租、几百G流量不限速不限量啥的&…

Cortex-A7支持的内存类型详解及配置举例

0 参考资料 Introduction to memory protection unit management on STM32 MCUs.pdf ARM ArchitectureReference Manual ARMv7-A and ARMv7-R edition.pdf 1 Cortex-A7支持的内存类型详解 1.1 内存类型 ARM架构处理器支持的内存类型分为三种&#xff0c;分别是Normal memory&…

airflow看不到任务日志解决方案

1. 基础信息 airflow 版本&#xff1a;2.5.3 2. 问题现象 airflow web-server 界面&#xff0c;看到某些任务的具体运行日志&#xff0c;只有少量日志&#xff0c;如下图所示&#xff1a; 具体日志内容如下&#xff1a; na-fudao-data-airflow-test-2-21.alibji.zybang.com…

某视频云平台存在未授权窃取用户凭据漏洞

我和你一样&#xff0c;历经破碎、痛苦的生活&#xff0c;却未垮掉&#xff0c;每一日都从承受的苦难中&#xff0c;再一次将额头浸入光明 漏洞详情&#xff1a; 某视频云平台存在未授权访问漏洞&#xff0c;攻击者可以直接访问平台的API接口文档&#xff0c;从而获取系统的A…

【大模型】Reflextion解读

前言&#xff1a;一种大模型强化学习技术&#xff0c;将传统的梯度更新时的参数信号替换成上下文的语言总结&#xff0c;过程和人类反思相似。区别与RLHF&#xff0c;Reflextion是agent自我反思&#xff0c;RLHF是人类反馈。 目录 1. 基础知识1.1 强化学习1.2 大模型Agent 2. 创…

Upload-LABS通关攻略【1-20关】

Pass-01 第一关是前端JS绕过 上传一个php文件显示只能上传特定后缀名的文件 这里将1.php改为1.jpg直接进行抓包&#xff0c;在数据包中将jpg改为php放行 文件上传成功&#xff0c;邮件图片新建页面打开 可以访问到1.php文件&#xff0c;则一句话密码上传成功 使用蚁剑 进行连接…

探秘DevSecOps黄金管道,安全与效率的完美融合

软件应用的安全性已成为企业和用户关注的焦点&#xff0c;DevSecOps作为一种将安全融入开发和运维全过程的理念和实践&#xff0c;旨在消除传统开发模式中安全被后置处理的弊端。DevSecOps黄金管道&#xff08;Golden Pipeline&#xff09;是实现这一理念的核心框架&#xff0c…

蜂鸣器奏乐

一、粗略了解简谱 拍号&#xff1a;如图&#xff0c;“2”表示一个小节有2拍&#xff0c;“4”表示4分音符为一拍 终止线表示歌曲结束 注意&#xff1a;以下音符都按以四分音符为一拍计算拍数 四分音符&#xff1a; 唱一拍 二分音符&#xff1a; 某一个音右边有一个小横线&…

OpenAI GPT3 Search API not working locally

题意&#xff1a;"OpenAI GPT-3 搜索 API 在本地无法工作" 问题背景&#xff1a; I am using the python client for GPT 3 search model on my own Jsonlines files. When I run the code on Google Colab Notebook for test purposes, it works fine and returns …

文件上传漏洞详解(持续更新…)

第一关 步骤一&#xff0c;打开第一关先点击浏览上传一个jpg格式的图片 步骤二&#xff0c;打开BP修改jpg为php然后放包 步骤三&#xff0c;右键打开图像 成功解析 步骤四&#xff0c;打开蚁剑 第一关还是蛮简单的 第二关 步骤一&#xff0c;打开第二关先点击浏览上传一个j…

leetcode637. 二叉树的层平均值,广度优先搜索BFS

leetcode637. 二叉树的层平均值 给定一个非空二叉树的根节点 root , 以数组的形式返回每一层节点的平均值。与实际答案相差 10-5 以内的答案可以被接受。 给定一个非空二叉树的根节点 root , 以数组的形式返回每一层节点的平均值。与实际答案相差 10-5 以内的答案可以被接受。…