克隆

来源:互联网 发布:linux服务器版本 编辑:程序博客网 时间:2024/04/28 23:18

【浅克隆】,通常只是对克隆的实例进行复制,但里面的其他子对象,都是共用的。

【深克隆】,克隆的时候会复制它的子对象的引用,里面所有的变量和子对象都是又额外拷贝了一份。

一、Cloneable接口实现深浅克隆

class Professor implements Cloneable 

String name; 
int age; 
Professor(String name,int age) 

this.name=name; 
this.age=age; 

public Object clone() 

Object o=null; 
try

o=super.clone(); 

catch(CloneNotSupportedException e) 

System.out.println(e.toString()); 

return o; 


public class Student implements Cloneable 

String name; 
int age; 
Professor p; 
Student(String name,int age,Professor p) 

this.name=name; 
this.age=age; 
this.p=p; 

public Object clone() 

Student o=null; 
try

o=(Student)super.clone(); 

catch(CloneNotSupportedException e) 

System.out.println(e.toString()); 

//对引用的对象也进行复制
o.p=(Professor)p.clone(); 
return o; 
}  
public static void main(String[] args) 

Professor p=new Professor("wangwu",50); 
Student s1=new Student("zhangsan",18,p); 
Student s2=(Student)s1.clone(); 
s2.p.name="lisi"; 
s2.p.age=30; 
//学生1的教授不 改变。
System.out.println("name="+s1.p.name+","+"age="+s1.p.age); 
System.out.println("name="+s2.p.name+","+"age="+s2.p.age); 

}


二、Serializable

class Teacher implements Serializable{
String name;
int age;
public void Teacher(String name,int age){
this.name=name;
this.age=age;
}
}
public class Student implements Serializable{
String name;//常量对象
int age;
Teacher t;//学生1和学生2的引用值都是一样的。
public void Student(String name,int age,Teacher t){
this.name=name;
this.age=age;
this.p=p;
}
public Object deepClone() throws IOException,
OptionalDataException,ClassNotFoundException{//将对象写到流里
ByteArrayOutoutStream bo=new ByteArrayOutputStream();
ObjectOutputStream oo=new ObjectOutputStream(bo);
oo.writeObject(this);//从流里读出来
ByteArrayInputStream bi=new ByteArrayInputStream(bo.toByteArray());
ObjectInputStream oi=new ObjectInputStream(bi);
return(oi.readObject());
}
public static void main(String[] args){ 
Teacher t=new Teacher("tangliang",30);
Student s1=new Student("zhangsan",18,t);
Student s2=(Student)s1.deepClone();
s2.t.name="tony";
s2.t.age=40;
//学生1的老师不改变
System.out.println("name="+s1.t.name+","+"age="+s1.t.age);
}
}

0 0
原创粉丝点击