Java中有兩種復(fù)制對象的方式,一種是淺拷貝,另一種是深拷貝。
淺拷貝是指拷貝一個對象,創(chuàng)建一個新對象,但這個新對象指向原對象的內(nèi)存空間,也就是說,新對象中的引用類型的成員變量和原對象中的成員變量指向同一個對象。
深拷貝是指拷貝一個對象,創(chuàng)建一個新對象,但這個新對象的引用類型的成員變量也要創(chuàng)建新的對象,即復(fù)制所有與原對象關(guān)聯(lián)的對象。
//淺拷貝demo class Person implements Cloneable { private String name; private Listhobbies; public Person(String name, List hobbies) { this.name = name; this.hobbies = hobbies; } public Object clone() throws CloneNotSupportedException { return super.clone(); } } List hobbies = new ArrayList<>(); hobbies.add("reading"); hobbies.add("swimming"); Person person1 = new Person("Tom", hobbies); Person person2 = (Person) person1.clone(); person1.getHobbies().add("running"); System.out.println(person2.getHobbies()); //輸出:[reading, swimming, running]
從上面的代碼可以看到,當(dāng)對person1的成員變量hobbies進(jìn)行修改時,person2的hobbies也受到影響,這就是淺拷貝。
//深拷貝demo class Person implements Cloneable { private String name; private Listhobbies; public Person(String name, List hobbies) { this.name = name; this.hobbies = hobbies; } public Object clone() throws CloneNotSupportedException { Person person = (Person) super.clone(); List hobbies = new ArrayList<>(); hobbies.addAll(this.getHobbies()); person.setHobbies(hobbies); return person; } public void setHobbies(List hobbies) { this.hobbies = hobbies; } public List getHobbies() { return hobbies; } } List hobbies = new ArrayList<>(); hobbies.add("reading"); hobbies.add("swimming"); Person person1 = new Person("Tom", hobbies); Person person2 = (Person) person1.clone(); person1.getHobbies().add("running"); System.out.println(person2.getHobbies()); //輸出:[reading, swimming]
從上面的代碼可以看到,當(dāng)對person1的成員變量hobbies進(jìn)行修改時,person2的hobbies不受到影響,這就是深拷貝。