浅拷贝、深拷贝
浅拷贝是指拷贝对象时仅仅拷贝对象本身(包括对象中的基本变量),而不拷贝对象包含的引用指向的对象。
深拷贝不仅拷贝对象本身,而且拷贝对象包含的引用指向的所有对象。
举例来说更加清楚:对象A1中包含对B1的引用,B1中包含对C1的引用。浅拷贝A1得到A2,A2 中依然包含对B1的引用,B1中依然包含对C1的引用。
深拷贝则是对浅拷贝的递归,深拷贝A1得到A2,A2中包含对B2(B1的copy)的引用,B2 中包含对C2(C1的copy)的引用。
若不对clone()方法进行改写,则调用此方法得到的对象即为浅拷贝
当然我们还有一种深拷贝方法,就是将对象串行化:private static final long serialVersionUID = 1L;
浅拷贝是指拷贝对象时仅仅拷贝对象本身(包括对象中的基本变量),而不拷贝对象包含的引用指向的对象。
深拷贝不仅拷贝对象本身,而且拷贝对象包含的引用指向的所有对象。
举例来说更加清楚:对象A1中包含对B1的引用,B1中包含对C1的引用。浅拷贝A1得到A2,A2 中依然包含对B1的引用,B1中依然包含对C1的引用。
深拷贝则是对浅拷贝的递归,深拷贝A1得到A2,A2中包含对B2(B1的copy)的引用,B2 中包含对C2(C1的copy)的引用。
若不对clone()方法进行改写,则调用此方法得到的对象即为浅拷贝
当然我们还有一种深拷贝方法,就是将对象串行化:private static final long serialVersionUID = 1L;
但是串行化却很耗时,在一些框架中,我们便可以感受到,它们往往将对象进行串行化后进行传递,耗时较多。
package org.javacore.base.copy;
/**
* @author Robin
* @since 2016-09-19 13:53:51
* 深拷贝与浅拷贝
*/
class Family implements Cloneable{
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
/**
* 深拷贝
* @return
*/
@Override
public Object clone() {
Object o = null;
try {
o = super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return o;
}
}
class Student implements Cloneable{
private String name;
private Family family;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Family getFamily() {
return family;
}
public void setFamily(Family family) {
this.family = family;
}
/**
* 浅拷贝 对其对象的引用却没有拷贝
* @return
* @throws CloneNotSupportedException
*/
// @Override
// protected Object clone() throws CloneNotSupportedException {
// return super.clone();
// }
/**
* 深拷贝
*/
@Override
protected Object clone() {
Student o = null;
try {
o = (Student)super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
o.family = (Family) family.clone();
return o;
}
}
public class CopyT {
public static void main(String[] args) throws CloneNotSupportedException {
Family family = new Family();
family.setName("Jeff Family");
Student student1 = new Student();
student1.setFamily(family);
student1.setName("Jeff");
Student student2 = (Student) student1.clone();
student2.setName("Jeff2");
student2.getFamily().setName("Jeff2 Family");
System.out.println(student1.getName() + " " + student1.getFamily().getName());
System.out.println(student2.getName() + " " + student2.getFamily().getName());
}
}
1491

被折叠的 条评论
为什么被折叠?



