Java深克隆和浅克隆

本文介绍了Java中的对象克隆,包括如何实现浅克隆和深克隆。通过实例展示了浅克隆只复制对象本身及基本变量,而深克隆则递归复制对象及其引用的对象。通过测试代码展示了深克隆如何确保原始对象修改不会影响到克隆后的对象。

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

Java深克隆和浅克隆

实现克隆

  1. 对象的类实现Cloneable接口;
  2. 覆盖Object类的clone()方法 ;
  3. 在clone()方法中调用super.clone();

浅克隆和深克隆

浅克隆是指拷贝对象时仅仅拷贝对象本身(包括对象中的基本变量),而不拷贝对象包含的引用指向的对象。

深克隆不仅拷贝对象本身,而且拷贝对象包含的引用指向的所有对象。

	@Data
    class Father implements Cloneable{
        private String name;
        private Integer age;
        @Override
        public Object clone() throws CloneNotSupportedException {
            return super.clone();
        }
    }
    @Test
    void testClone() throws CloneNotSupportedException {
        Father father = new Father();
        father.setName("zs");
        father.setAge(18);
        Father clone = (Father) father.clone();
        father.setName("ls");
        System.out.println(father);//Father(name=ls, age=18)
        System.out.println(clone);//Father(name=zs, age=18)
    }
//注意修改father的name值 但是没有影响 clone的值
@Data
    class Father implements Cloneable{
        private String name;
        Child child;
        @Override
        public Object clone() throws CloneNotSupportedException {
            Father father = (Father)super.clone();
            father.setChild((Child)father.getChild().clone());
            return father;
        }
    }
@Data
    class Child implements Cloneable{
        private String name;
        private Integer age;

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


    @Test
    void testClone() throws CloneNotSupportedException {
        Father father = new Father();
        father.setName("zs");

        Child child = new Child();
        child.setName("儿子");
        child.setAge(15);

        father.setChild(child);

        Father clone = (Father) father.clone();
        Child child1 = father.getChild();
        child1.setName("儿子2");
        father.setChild(child1);

        System.out.println();
        System.out.println(father);//Child(name=儿子2, age=15))
        System.out.println(clone);//Child(name=儿子, age=15))
//此时修改原来对象的值,是不会影响复制的对象的
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值