深拷贝和浅拷贝
java代码实现
浅拷贝:你获取teacher1拷贝后的对象teacher2,你使用teacher2去修改某个引用对象会改变之前的对象的引用,相当于将teacher2的引用指向teacher的对象引用。深拷贝就不会,相当于复制了一份过来。
但是如果是基本数据类型:不管深拷贝、浅拷贝都不会改变之前的,因为基础类型克隆的是值。
如果是String或者Integer这种包装类型:不管深拷贝、浅拷贝都不会改变之前的。因为他们都是不可变类。
string我就不截图了,Integer图:
package tempTest; import java.util.ArrayList; import java.util.List; public class CopyTest { public static void main(String[] args) throws Exception { Teacher teacher = new Teacher("王老师",41); Student student1 = new Student("陶同学",22); //Student student2 = new Student("黄同学",21); teacher.setStudent(student1); Teacher teacher2 = (Teacher) teacher.clone(); teacher2.setName("陶老师"); System.out.println("克隆后的打印被克隆的王老师和克隆产生的陶老师--------"); System.out.println(teacher.getName()+"的学生:"+teacher.getStudent().getName()); System.out.println(teacher2.getName()+"的学生:"+teacher2.getStudent().getName()); teacher2.getStudent().setName("龚同学"); System.out.println("给第二个老师将学生姓名改为龚同学-----"); System.out.println(teacher.getName()+"的学生:"+teacher.getStudent().getName()); System.out.println(teacher2.getName()+"的学生:"+teacher2.getStudent().getName()); } } class Teacher implements Cloneable{ private String name; private int age; private Student student; @Override public Object clone() throws CloneNotSupportedException {
//深拷贝 Teacher teacher = (Teacher) super.clone(); teacher.student = (Student) student.clone(); return teacher;
//浅拷贝return super.clone } } class Student implements Cloneable{ private String name; private int age; @Override public Object clone() throws CloneNotSupportedException { return super.clone(); } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)