一、克隆的兩種方式。java
a、淺度克隆。讓須要你須要克隆的類實現Cloneable這個接口。在調用super.clone這個方法完成克隆。代碼以下this
public class User implements Cloneable{ private String name; private String address; private Dog dog; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public Dog getDog() { return dog; } public void setDog(Dog dog) { this.dog = dog; } public Object getObject(){ Object obj=null; try { obj=super.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } return obj; } } public class Dog { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } }
b、深度克隆。讓你須要克隆的類以及該類設計的全部類都要實現Serializable這個標記性接口。讓後進行流操做,完成克隆。代碼以下:設計
public class User implements Serializable{ private String name; private String address; private Dog dog; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public Dog getDog() { return dog; } public void setDog(Dog dog) { this.dog = dog; } public Object deepClone(){ Object obj=null; try { ByteArrayOutputStream bos=new ByteArrayOutputStream(); ObjectOutputStream oos=new ObjectOutputStream(bos); oos.writeObject(this); ByteArrayInputStream bis=new ByteArrayInputStream(bos.toByteArray()); ObjectInputStream ois=new ObjectInputStream(bis); obj=ois.readObject(); } catch (Exception e) { e.printStackTrace(); } return obj; } } public class Dog implements Serializable { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } }
綜上所述,咱們不難發現,淺度克隆其實就是把你須要克隆的類徹底的複製一份。而深度克隆則是把該類的屬性和方法進行復制,引用的其餘類則是新的對象。code