一、概念
1、浅拷贝:对基本数据类型进行值传递,对引用数据类型进行引用传递般的拷贝,此为浅拷贝。
2、深拷贝:对基本数据类型进行值传递,对引用数据类型,创建一个新的对象,并复制其内容,此为深拷贝。
二、图解
(1)浅拷贝:
(2)深拷贝:
三、实例
public class mytest {
public static void main(String[] args) {
Parent item1 = new Parent(“john”, 10);
Parent item2 = item1.clone();
System.out.println("parent1 = " + item1.toString());
System.out.println("parent2 = " + item2.toString());
}
public static class Parent implements Cloneable{
String name = "";
int age = 0;
Parent (String n, int age){
this.name = n;
this.age = age;
}
public void setName(String na) {
name = na;
}
@Override
protected Parent clone() {
Parent clone = null;
try {
clone = (Parent) super.clone();
} catch (CloneNotSupportedException e){
throw new RuntimeException(e); // won't happen
}
return clone;
}
public String toString() {
return "Parent[" + name + "===" + age + "];";
}
}
}
运行结果:
parent1 = Parent[john=10];
parent2 = Parent[john=10];
Parent1被复制了一份。
添加一个内部类son,并加到parent里头去。
[java] view plain copy
public class mytest {
。。。。。。。。
public static class Parent implements Cloneable{
String name = “”;
int age = 0;
Son theson;
Parent (String n, int age){
this.name = n;
this.age = age;
}
public void setName(String na) {
name = na;
}
public void setSon(Son s) {
theson = s;
}
@Override
protected Parent clone() {
Parent clone = null;
try {
clone = (Parent) super.clone();
} catch (CloneNotSupportedException e){
throw new RuntimeException(e); // won't happen
}
return clone;
}
public String toString() {
return "Parent[" + name + "===" + age + "];" + "---Son:"+ (theson != null ? theson.name : "null");
}
}
public static class Son implements Cloneable {
String name = "";
int age = 0;
Son (String n, int age){
this.name = n;
this.age = age;
}
public void setName(String na) {
name = na;
}
@Override
protected Son clone() {
Son clone = null;
try {
clone = (Son) super.clone();
} catch (CloneNotSupportedException e){
throw new RuntimeException(e); // won't happen
}
return clone;
}
public String toString() {
return "Son[" + name + "===" + age + "];";
}
}
}
测试结果:
parent1与parent2中的son都变了。
可见,浅拷贝只是将内部对象的地址保存