设计模式-原型模式(深拷贝) #java基础#设计模式

本文详细解析了浅拷贝与深拷贝的区别,浅拷贝仅复制对象的基本数据类型及其封装类,而深拷贝则会递归复制所有引用对象,确保完全独立。文章通过具体代码示例展示了如何在Java中实现这两种拷贝方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

浅拷贝:拷贝了对象的基本数据类型或其封装类,对于内部的数组、引用对象  依旧是采用引用的形式;

@Data
public class TestEntity implements Cloneable{
    private String testAid;
    private String testAname;
    private TestEntityB testEntityB;

    public TestEntity(){
    }

    @Override
    protected TestEntity clone() {
        TestEntity testEntity = null;
        try {
            testEntity = (TestEntity)super.clone();
         /*   testEntity.testEntityB = (TestEntityB)this.getTestEntityB().clone();*/
        } catch (CloneNotSupportedException e) {
            //异常处理
        }
        return testEntity;
    }

运行结果:

虽然克隆后 a==a3为false,已经是指向不同的引用地址了, 但是其内部的对象entityB依旧指向相同的地址;这种clone方式叫浅拷贝。

深拷贝:对私有的数组,引用对象也会进行拷贝,引用不同的地址;

  

@Data
public class TestEntity implements Cloneable{
    private String testAid;
    private String testAname;
    private TestEntityB testEntityB;

    public TestEntity(){
    }

    @Override
    protected TestEntity clone() {
        TestEntity testEntity = null;
        try {
            testEntity = (TestEntity)super.clone();
            testEntity.testEntityB = (TestEntityB)this.getTestEntityB().clone(); //激活代码
        } catch (CloneNotSupportedException e) {
            //异常处理
        }
        return testEntity;
    }

@Data
public class TestEntityB   implements Cloneable  {
    private String testBId;
    private String testBname;

    @Override
    protected TestEntityB clone() {
        TestEntityB testEntityB = null;
        try {
            testEntityB =  (TestEntityB)super.clone();
        } catch (CloneNotSupportedException e) {

        }

        return testEntityB;
    }

运行结果: 

注意:咱们的被引用类如果要使用clone方法必须也要实现Cloneable接口。 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值