首页 > 其他分享 >深克隆的实现方式

深克隆的实现方式

时间:2024-04-17 12:34:32浏览次数:19  
标签:克隆 方式 实现 name Address id address public String

1. 所有对象都实现克隆方法

2. 通过构造方法实现深克隆

3. 使用JDK自带的字节流实现深克隆

(1)所有对象都实现克隆方法,这种方式需要让所有的引用对象都实现克隆(Cloneable 接口)

点击查看代码
package com.clone;

public class CloneExample {

    public static void main(String[] args) throws CloneNotSupportedException {
        //创建被赋值对象
        Address address=new Address(001,"北京");
        People p1=new People(1,"Java",address);
        //克隆p1对象
        People p2 = p1.clone();
        //修改原型对象
        p2.getAddress().setCity("深圳");
        //输出p1和p2地址信息
        System.out.println("p1:" +p1.getAddress().getCity()+"p2:"+p2.getAddress().getCity());

    }


    static class People implements Cloneable{
        private Integer id;
        private String name;
        private Address address;

        @Override
        protected People clone() throws CloneNotSupportedException {
            People people = (People) super.clone();
            people.setAddress(this.address.clone());
            //引用类型克隆赋值
            return people;
        }

        public Integer getId() {
            return id;
        }

        public void setId(Integer id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public Address getAddress() {
            return address;
        }

        public void setAddress(Address address) {
            this.address = address;
        }

        public People(Integer id, String name, Address address) {
            this.id = id;
            this.name = name;
            this.address = address;
        }


    }

    static class Address implements Cloneable{
        private Integer id;
        private String city;

        public Address(Integer id, String city) {
            this.id = id;
            this.city = city;
        }

        public Integer getId() {
            return id;
        }

        public void setId(Integer id) {
            this.id = id;
        }

        public String getCity() {
            return city;
        }

        public void setCity(String city) {
            this.city = city;
        }

        @Override
        protected Address clone() throws CloneNotSupportedException {
            return(Address)super.clone();
        }
    }

}


(2)通过构造方法实现深克隆

点击查看代码
package com.clone;

public class SecondExample {
    public static void main(String[] args) {
        //创建对象
        Address address=new Address(001,"北京");
        People p1=new People(1,"Java",address);
        //调用构造函数克隆对象
        //如果构造器的参数为基本数据类型或字符串类型则直接赋值,如果是对象类型,则需要重新 new 一个对象
        People p2 = new People(p1.getId(), p1.getName(), new Address(p1.getAddress().getId(), p1.getAddress().getCity()));
        //修改原型对象
        p1.getAddress().setCity("广州");
        //输出p1和p2地址信息
        System.out.println("p1:"+p1.getAddress().getCity()+"p2:"+p2.getAddress().getCity());
    }

    static class People {
        private Integer id;
        private String name;
        private Address address;


        public Integer getId() {
            return id;
        }

        public void setId(Integer id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public Address getAddress() {
            return address;
        }

        public void setAddress(Address address) {
            this.address = address;
        }

        public People(Integer id, String name, Address address) {
            this.id = id;
            this.name = name;
            this.address = address;
        }


    }
    static class Address {
        private Integer id;
        private String city;

        public Address(Integer id, String city) {
            this.id = id;
            this.city = city;
        }

        public Integer getId() {
            return id;
        }

        public void setId(Integer id) {
            this.id = id;
        }

        public String getCity() {
            return city;
        }

        public void setCity(String city) {
            this.city = city;
        }

    }
}

(3)使用JDK自带的字节流实现深克隆

点击查看代码
package com.clone;

import java.io.*;

public class ThirdExample {
    public static void main(String[] args) {
        //创建对象
        Address address = new Address(001, "北京");
        People p1 = new People(1, "java", address);
        //通过字节流实现克隆
        People p2 = (People) StreamClone.clone(p1);
        //修改原型对象
        p1.getAddress().setCity("上海");
        //输出p1和p2地址信息
        System.out.println("p1:"+p1.getAddress().getCity()+"p2:"+p2.getAddress().getCity());


    }
    static class StreamClone{
        public static <T extends Serializable> T clone(People obj){
            T cloneObj=null;
            try {
                ByteArrayOutputStream bo = new ByteArrayOutputStream();
                ObjectOutputStream oos = new ObjectOutputStream(bo);
                oos.writeObject(obj);
                oos.close();
                //分配内存,写入原始对象,生成新对象
                ByteArrayInputStream bi = new ByteArrayInputStream(bo.toByteArray());
                //获取上面的输出字节流
                ObjectInputStream oi = new ObjectInputStream(bi);
                //返回生成新的对象
                cloneObj=(T) oi.readObject();
                oi.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return cloneObj;

        }
    }

    static class People  implements Serializable {
        private Integer id;
        private String name;
        private Address address;



        public Integer getId() {
            return id;
        }

        public void setId(Integer id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public Address getAddress() {
            return address;
        }

        public void setAddress(Address address) {
            this.address = address;
        }

        public People(Integer id, String name, Address address) {
            this.id = id;
            this.name = name;
            this.address = address;
        }


    }
    static class Address implements Serializable{
        private Integer id;
        private String city;

        public Address(Integer id, String city) {
            this.id = id;
            this.city = city;
        }

        public Integer getId() {
            return id;
        }

        public void setId(Integer id) {
            this.id = id;
        }

        public String getCity() {
            return city;
        }

        public void setCity(String city) {
            this.city = city;
        }

    }
}

标签:克隆,方式,实现,name,Address,id,address,public,String
From: https://www.cnblogs.com/yumeixiaosheng/p/18140298

相关文章

  • Qt实现无边框窗口(二)
    本例使用纯Qt实现了无边框的窗口,包含了窗口外围的阴影和调整窗口大小的功能,以及最小化、最大化和关闭按钮的功能。本程序在VS2017、Qt5.9下测试通过。期间为了正确响应鼠标消息调试了1~2天,因为在推拽调整窗口大小的时候总是会出漏洞,不过最终还是解决了这些问题。运行效果如下图:......
  • SQL Server安装以及使用Navicat连接遇到的问题的解决方式
    1、SQLServer安装,参考连接:SQLServer2019安装详细教程(图文详解,非常靠谱)2、远程服务器:Navicat连接报错:TCP提供程序:由于目标计算机积极拒绝,无法连接.该错误有2个方面的问题需要解决(1)远程服务器是否能够telnet服务器的ip和端口, 解决方式:在SQLServer服务器的防火墙中增......
  • Data studio普通用户采用非SSL的方式连接openGauss
    Datastudio普通用户采用非SSL的方式连接openGauss关闭SSL认证由于openGauss默认开启SSL认证,且配置认证较为麻烦,个人开发测试并不需要它。因此关闭openGauss的远程用户登录SSL认证模式。1.找到postgresql.conf。cd/gaussdb/data/openGaussTest1/2.修改postg......
  • 小程序上实现房贷计算
    功能:实现房贷计算,区分等额本息,等额本金,查看月供详情效果图组件存放路径components/h-chosen使用VantWeapp:https://vant-contrib.gitee.io/vant-weapp/#/homeindex.wxml<!--components/h-chosen/index.wxml--><view><van-cellrequired="{{required}}"t......
  • Avalonia实现Visual Studio风格标题栏的方法
       VisualStudio风格的标题栏可以更节省屏幕空间,个人认为其实比Ribbonbar和传统菜单都要更先进一些,更紧凑,利用效率更高。我在AvaloniaSamples项目中添加了一个这种Demo,展示了如何在Avalonia11中分别实现经典风格、Macos风格和VisualStudio风格的标题栏:    ......
  • 基于Redis实现基本抢红包算法
    简介:[key,value]的缓存数据库,Redis官方性能描述非常高,所以面对高并发场景,使用Redis来克服高并发压力是一个不错的手段,本文主要基于Redis来实现基本的抢红包系统设计.发红包模块:1:发红包模块流程图如下:  用户首先输入红包金额和红包个数,然后生成当前红......
  • 小程序上是实现拖动悬浮图标
    小程序上是实现拖动图标效果index.wxml<view><viewclass="move-box"catchtouchmove="buttonMove"bindtouchstart="buttonStart"style="top:{{buttonTop}}px;left:{{buttonLeft}}px;">悬浮图标......
  • IaC:实现持续交付和 DevOps 自动化的关键
    基础架构即代码(IaC)和CI/CD流水线最初似乎并不匹配。因为它们代表了两种不同的流程。IaC主要关注基础设施的配置和开发,而CI/CD则围绕软件开发、测试和部署。 然而,将IaC集成到CI/CD流水线中具有多种优势。首先,它可以将新资源调配到部署流程中。此外,一旦资源使用完毕,就能......
  • 3-04. 实现箱子储物空间的保存和数据交换
    实现箱子与背包数据交换修改SlotUI修改InventoryManager修改SlotUI实现箱子数据保存目标当场景切换之后,箱子里面的数据不能丢失修改InventoryManager修改Box修改InventoryManager修改Box修改DataCollection修改ItemManager修改Box修改It......
  • 实现一个前向渲染的Phong模型(一)
    标准Phong模型实现Shader"Unlit/PhongJian"{Properties{_MainTex("Texture",2D)="white"{}_Shininess("Shininess",Range(0.01,100))=1.0//高光亮度对比度_SpecIntensity("SpecInten......