在Java中,對象的克隆一般分為淺克隆和深度克隆。
淺克隆指的是一個對象通過clone()方法復制自身,但并不會復制引用的對象,而是將這些引用直接指向原來的對象。
class Person implements Cloneable { private String name; private Address address; //省略構造方法和getter/setter方法 @Override public Person clone() throws CloneNotSupportedException { return (Person) super.clone(); } } class Address { private String city; private String street; //省略構造方法和getter/setter方法 } public static void main(String[] args) throws CloneNotSupportedException { // original Person Person person = new Person("Tom", new Address("Beijing", "Main Street")); // clone Person Person clone = person.clone(); // change clone's Address clone.getAddress().setCity("Shanghai"); System.out.println(person.getAddress().getCity()); // 輸出 Shanghai }
可以看到,當我們修改clone對象中的address時,原對象person的address也被修改了,這是因為clone對象和原對象的address引用指向的是同一個對象。
深度克隆則是將對象的引用對象也進行克隆,使得新克隆的對象和原對象完全獨立。
class Person implements Cloneable { private String name; private Address address; //省略構造方法和getter/setter方法 @Override public Person clone() throws CloneNotSupportedException { Person clone = (Person) super.clone(); clone.setAddress(this.address.clone()); return clone; } } class Address implements Cloneable { private String city; private String street; //省略構造方法和getter/setter方法 @Override public Address clone() throws CloneNotSupportedException { return (Address) super.clone(); } } public static void main(String[] args) throws CloneNotSupportedException { // original Person Person person = new Person("Tom", new Address("Beijing", "Main Street")); // clone Person Person clone = person.clone(); // change clone's Address clone.getAddress().setCity("Shanghai"); System.out.println(person.getAddress().getCity()); // 輸出 Beijing }
可以看到,當我們修改clone對象中的address時,原對象person的address并沒有被修改,這是因為clone對象和原對象的address引用指向的是不同的對象。