Java中對(duì)象的拷貝操作是非常常見的,其中包括淺拷貝和深拷貝。下面是對(duì)這兩種拷貝方式的詳細(xì)介紹。
淺拷貝
淺拷貝是指在拷貝對(duì)象時(shí),僅拷貝對(duì)象的基本屬性或引用值,而不是拷貝引用的目標(biāo)對(duì)象。例如:
public class Person { private String name; private Address address; // getters and setters public Person shallowCopy() { Person person = new Person(); person.setName(this.name); person.setAddress(this.address); // 只拷貝了地址引用 return person; } } public class Address { private String street; private String city; private String zip; // getters and setters } Person john = new Person(); john.setName("John"); john.setAddress(new Address("123 Main St", "Anytown", "12345")); Person jane = john.shallowCopy(); jane.getAddress().setStreet("456 Other St"); // 改變了jane的地址屬性,但同時(shí)也改變了john的地址屬性
從上述代碼可以看出,當(dāng)我們對(duì)淺拷貝的目標(biāo)對(duì)象的屬性進(jìn)行修改時(shí),原始對(duì)象的屬性也會(huì)被修改。
深拷貝
深拷貝是對(duì)對(duì)象的完全拷貝,包括引用目標(biāo)對(duì)象。例如:
public class Person { private String name; private Address address; // getters and setters public Person deepCopy() { Person person = new Person(); person.setName(this.name); Address address = new Address(); address.setStreet(this.address.getStreet()); address.setCity(this.address.getCity()); address.setZip(this.address.getZip()); person.setAddress(address); // 拷貝了整個(gè)Address對(duì)象 return person; } } Person john = new Person(); john.setName("John"); john.setAddress(new Address("123 Main St", "Anytown", "12345")); Person jane = john.deepCopy(); jane.getAddress().setStreet("456 Other St"); // 只改變了jane的地址屬性,不會(huì)影響john的地址屬性
從上述代碼可以看出,深拷貝會(huì)完全復(fù)制對(duì)象,不會(huì)與原始對(duì)象共享同一個(gè)引用目標(biāo)對(duì)象。