标签:clone
浅拷贝:
(1) 基本的数据类型(String)是会拷贝复制一份新的对象
(2)引用对象还是引用同一份对象。
浅拷贝示例代码:
public class Info {最后的结果是:
public int idnumber;
public int getIdnumber() {
return idnumber;
}
public void setIdnumber(int idnumber) {
this.idnumber = idnumber;
}
}
public class Person implements Cloneable{
private int age;
private String nameString;
public Info info;
public Info getInfo() {
return info;
}
public void setInfo(Info info) {
this.info = info;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getNameString() {
return nameString;
}
public void setNameString(String nameString) {
this.nameString = nameString;
}
public String toString()
{
return "name:"+nameString+",age:"+age+",idnumber"+info.idnumber;
}
public Object clone()
{
Person person=null;
try {
person=(Person)super.clone(); //浅拷贝
//person.info=(Info)info.clone();
} catch (CloneNotSupportedException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
return person;
}
}
public class Hello {
public static void main(String[] args) {
// TODO 自动生成的方法存根
Info info=new Info();
info.setIdnumber(100);
Person person1=new Person();
person1.setAge(10);
person1.setNameString("tiantian");
person1.info=info;
Person person2=(Person)person1.clone();
person2.setNameString("hello");
person2.setAge(20);
person2.info.setIdnumber(200);
System.out.println("person2"+person2);
System.out.println("person1"+person1);
}
}
person2name:hello,age:20,idnumber200person1和person2的基本类型name和age都改变了,但引用类型的idnumber数值没变。
person1name:tiantian,age:10,idnumber200
深拷贝:
(1)对存在的引用类型也进行拷贝,浅拷贝与深拷贝的代码还是有不同点的。
深拷贝代码示例:
public class Info implements Cloneable {//Info也进行拷贝结果:
public int idnumber;
public int getIdnumber() {
return idnumber;
}
public void setIdnumber(int idnumber) {
this.idnumber = idnumber;
}
public Object clone()
{
Info info=null;
try {
info=(Info)super.clone();
} catch (CloneNotSupportedException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
return info;
}
}
public class Person implements Cloneable{
private int age;
private String nameString;
public Info info;
public Info getInfo() {
return info;
}
public void setInfo(Info info) {
this.info = info;
}
public Person() {
// TODO 自动生成的构造函数存根
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getNameString() {
return nameString;
}
public void setNameString(String nameString) {
this.nameString = nameString;
}
public String toString()
{
return "name:"+nameString+",age:"+age+",idnumber"+info.idnumber;
}
public Object clone()
{
Person person=null;
try {
person=(Person)super.clone(); //浅拷贝
person.info=(Info)info.clone();//加上这一句就变成了深拷贝,对对象引用也进行一次拷贝
} catch (CloneNotSupportedException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
return person;
}
}
person2name:hello,age:20,idnumber200所有的值都进行了改变。
person1name:tiantian,age:10,idnumber100
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:clone
原文地址:http://blog.csdn.net/qq924862077/article/details/48022247