栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

浅拷贝和深拷贝

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

浅拷贝和深拷贝

拷贝的引用 引用拷贝

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

//引用拷贝
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
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/328373.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号