深度克隆和浅度克隆的总结
克隆的主对象:(重写了clone方法)
public class TestClonBean implements Cloneable,Serializable{private String name;private int age;private String sex;@Overrideprotected TestClonBean clone(){TestClonBean bean = null;try {bean = (TestClonBean) super.clone();} catch (CloneNotSupportedException e) {// TODO Auto-generated catch blocke.printStackTrace();}return bean;}省略get/set方法……}
public class TestCloneChildBean implements Cloneable,Serializable{private String cname;private String csex;private int cage;省略get/set方法……}
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 blocke.printStackTrace();} catch (ClassNotFoundException e) {// TODO Auto-generated catch blocke.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;}}