Java中的克隆分為深克隆和淺克隆兩種,二者在實現(xiàn)方式與效果上都存在較大差別。
淺克隆是通過復制對象本身以及其所有的基本數(shù)據(jù)類型的屬性值,而不是復制屬性指向的對象,也就是說,淺克隆只是復制了對象的引用地址,并沒有真正的克隆完整的對象。淺克隆通常通過實現(xiàn)Cloneable接口和重寫Object類中clone方法實現(xiàn)。
public class Person implements Cloneable { private String name; private int age; private Listhobbies; public Person(String name, int age, List hobbies) { this.name = name; this.age = age; this.hobbies = hobbies; } public Person clone() throws CloneNotSupportedException { Person person = (Person) super.clone(); return person; } }
深克隆則是完全復制對象,不論是對象本身還是對象的引用都進行一次完整的復制。深克隆通常需要對每一個被克隆的類進行重新實現(xiàn),通過重寫序列化接口,利用對象的序列化和反序列化來實現(xiàn)深克隆。
public class Person implements Serializable { private String name; private int age; private Listhobbies; public Person(String name, int age, List hobbies) { this.name = name; this.age = age; this.hobbies = hobbies; } public Person clone() throws IOException, ClassNotFoundException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(this); ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); ObjectInputStream ois = new ObjectInputStream(bais); return (Person)ois.readObject(); } }
深克隆和淺克隆都有各自的應用場景,根據(jù)需求進行選擇即可。