浅拷贝与深拷贝的区别
浅拷贝:
首先会创建一个对象,然后如果对象中包含引用,只会是引用拷贝,并不会复制引用实际指向的对象,也就是说源对象和新对象指向的引用是同一个地址,任何一个修改都会影响的
深拷贝
首先也是会创建一个对象,除了复制对象的引用外,还会去递归的创建引用所指向的实际对象,在堆中会去重新拷贝一个新的对象的。双方是互不影响的 !!!
实现拷贝的方法:
实现 Cloneable 接口去重写里面的clone 方法即可,只要是引用的对象,都可以去重写这方法默认是浅拷贝 !!!
序列化反序列化来实现
参考代码:
package theMap;
public class Copy {
static class Student implements Cloneable {
String name;
int age;
Where Where ;
public Student() {
}
public Student(String name, int age, Copy.Where where) {
this.name = name;
this.age = age;
Where = where;
}
@Override
protected Student clone() throws CloneNotSupportedException {
Student student = (Student) super.clone();
student.Where = (Where) this.Where.clone();
return student;
}
}
static class Where implements Cloneable {
String name;
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
public static void main(String[] args) throws CloneNotSupportedException {
Student student = new Student("张三",20,new Where());
Student student1 = student.clone();
System.out.println(student +"新 "+ student1);
System.out.println(student == student1);
System.out.println(student.Where + " 新" + student1.Where);
System.out.println(student.Where == student1.Where);
}
}
输出样例
theMap.Copy$Student@4f3f5b24新 theMap.Copy$Student@15aeb7ab
false
theMap.Copy$Where@7b23ec81 新theMap.Copy$Where@6acbcfc0
false
图片

本文是原创文章,采用 CC BY-NC-ND 4.0 协议,完整转载请注明来自 程序员阿政
评论
匿名评论
隐私政策
你无需删除空行,直接评论以获取最佳展示效果