浅拷贝和深拷贝

拷贝的引用

引用拷贝

引用变量拷贝:创建一个指向对象的引用变量的拷贝

//引用拷贝
Teacher t = new Teacher();
Teacher tCopy = t;
System.out.println(t);
System.out.println(tCopy);

com.entity.Teacher@4f023edb
com.entity.Teacher@4f023edb

对象拷贝

  • 定义
    • 创建对象本身的一个副本
    • 被拷贝的对象对应的类要实现 cloneable 接口
    • 重写Object 类的clone 方法,并且将方法修饰符改为 public

浅拷贝

被复制对象的所有变量都含有与原对象相同的值,而所有的对其他对象的引用仍然指向原来的对象。即对象的浅拷贝只会对“主”对象进行拷贝,但不会复制对象里面的对象。里面的对象会在原来的主对象和主对象副本之间共享。

简单说:浅拷贝仅仅复制所拷贝的对象,对象里引用的对象不拷贝,由新老对象共享。

 ```java
 //浅拷贝
	Teacher t1 = new Teacher();
	t1.setName("1");
	t1.setAge(11);
	Student student = new Student();
	student.setScore(11);
	t1.setStudent(student);
	try {
		Teacher t2 = (Teacher) t1.clone();
		System.out.println("浅拷贝原对象:" + t1);
		System.out.println("浅拷贝新对象:" + t2);
		System.out.println("原对象中的属性指向的对象:" + t1.getStudent());
		System.out.println("新对象中的属性指向的对象:" + t2.getStudent());
	} catch (CloneNotSupportedException e) {
		e.printStackTrace();
	}
	//具体的teacher 类 
	// 实现 Cloneable 接口
	public class Teacher implements Cloneable{
	private String name;

	private int age;

	private Student student;

	@Override  重写这个方法 浅拷贝的实现
	public Object clone() throws CloneNotSupportedException {
		return super.clone();
	}
	//输出结果为
	 浅拷贝原对象:com.entity.Teacher@3a71f4dd
	 拷贝新对象:com.entity.Teacher@7adf9f5f
	 原对象中的属性指向的对象:com.entity.Student@85ede7b
	 新对象中的属性指向的对象:com.entity.Student@85ede7b
 ```

深拷贝

整体独立的对象拷贝,深拷贝会拷贝所有的属性,并拷贝属性指向的动态分配的内存。当对象和它所引用的对象一起拷贝时即发生浅拷贝。深拷贝相比于浅拷贝速度较慢并且花销较大。
简而言之,深拷贝要复制对象的对象所引用的对象都复制了一遍。

//深拷贝
	Teacher2 t3 = new Teacher2();
	t3.setName("1");
	t3.setAge(11);
	Student student2 = new Student();
	student.setScore(11);
	t3.setStudent(student2);
	try {
		Teacher2 t4 = (Teacher2) t3.clone();
		System.out.println("深拷贝原对象:" + t3);
		System.out.println("深拷贝新对象:" + t4);
		System.out.println("原对象中的属性指向的对象:" + t3.getStudent());
		System.out.println("新对象中的属性指向的对象:" + t4.getStudent());
	} catch (CloneNotSupportedException e) {
		e.printStackTrace();
	}
// Teacher2 类中对属性对象进行深拷贝
	@Override 深复制
	public  Object clone() throws CloneNotSupportedException {
		//改为深复制
		Teacher2 teacher = (Teacher2) super.clone();
		teacher.setStudent((Student) teacher.getStudent().clone());
		return teacher;
	}
	//输出结果为
	深拷贝原对象:com.entity.Teacher2@5674cd4d
	深拷贝新对象:com.entity.Teacher2@63961c42
	原对象中的属性指向的对象:com.entity.Student@65b54208
	新对象中的属性指向的对象:com.entity.Student@1be6f5c3
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值