深さクローンと浅さクローンのまとめ
3083 ワード
クローンのプライマリオブジェクト:(cloneメソッドを書き換えた)
クローンの依存:
深度クローンのツールクラス:
(深度クローンの原理:オブジェクトをシーケンス化してメモリに出力し、メモリからシーケンス化されたbyte[]を取り出し、逆シーケンス化してオブジェクトを取得する)
テスト:
まとめ:
深さクローンでも浅さクローンでも、実際には新しいオブジェクトが生成されます.クローンオブジェクトとソースオブジェクトを比較するときにfalseを返します.深度クローンと浅さクローンの違いは、浅さクローンのオブジェクトは通常のプロパティのみをクローンし、オブジェクトのプロパティはクローンしません.深度クローンは、オブジェクトのアトリビュートとともにクローンされます.したがって、比較深さクローンにおけるtt 1.getChild()==tcbclone.getChild()の場合、falseを返します.一方、浅いクローンではtrueが返されます.
public class TestClonBean implements Cloneable,Serializable{
private String name;
private int age;
private String sex;
@Override
protected TestClonBean clone(){
TestClonBean bean = null;
try {
bean = (TestClonBean) super.clone();
} catch (CloneNotSupportedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return bean;
}
get/set ……
}
クローンの依存:
public class TestCloneChildBean implements Cloneable,Serializable{
private String cname;
private String csex;
private int cage;
get/set ……
}
深度クローンのツールクラス:
(深度クローンの原理:オブジェクトをシーケンス化してメモリに出力し、メモリからシーケンス化されたbyte[]を取り出し、逆シーケンス化してオブジェクトを取得する)
public class DeepCloneBean {
public static Object getObject(Object obj){
Object cloneobj = null;
ByteArrayInputStream bin = null;
ByteArrayOutputStream bout = null;
try {
//
bout = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bout);
oos.writeObject(obj);
oos.close();
//
ByteArrayInputStream bais = new ByteArrayInputStream(bout.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bais);
cloneobj = ois.readObject();
ois.close();
return cloneobj;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
テスト:
public class TestClone {
public static void main(String []args){
//
TestCloneChildBean tcc = new TestCloneChildBean();
TestCloneChildBean tcc1 = tcc.clone();
System.out.println(tcc==tcc1);//result:false;
TestClonBean tcb = new TestClonBean();
tcb.setChild(tcc);
TestClonBean tcb1 = tcb.clone();
System.out.println(tcb==tcb1);//result:false;
System.out.println(tcb.getChild()==tcb1.getChild());//result:true;
System.out.println("***************** ************");
//
TestClonBean tt1 = new TestClonBean();
TestCloneChildBean tc1 = new TestCloneChildBean();
tt1.setChild(tc1);
TestClonBean tcbclone = (TestClonBean) DeepCloneBean.getObject(tt1);
System.out.println(tt1==tcbclone);//result:false;
System.out.println(tt1.getChild()==tcbclone.getChild());//result:false;
}
}
まとめ:
深さクローンでも浅さクローンでも、実際には新しいオブジェクトが生成されます.クローンオブジェクトとソースオブジェクトを比較するときにfalseを返します.深度クローンと浅さクローンの違いは、浅さクローンのオブジェクトは通常のプロパティのみをクローンし、オブジェクトのプロパティはクローンしません.深度クローンは、オブジェクトのアトリビュートとともにクローンされます.したがって、比較深さクローンにおけるtt 1.getChild()==tcbclone.getChild()の場合、falseを返します.一方、浅いクローンではtrueが返されます.