欧美一区二区三区,国内熟女精品熟女A片视频小说,日本av网,小鲜肉男男GAY做受XXX网站

java 什么是淺拷貝和深拷貝

吉茹定2年前8瀏覽0評論

在Java中,我們通常需要復制對象。對象復制有兩種方式:淺復制和深復制。這兩種方式的主要區別在于復制模式所涉及的對象的層數。在下面的段落中,我們將探討淺復制和深復制的定義,以及它們如何區別。

淺復制是指僅復制對象本身以及其中包含的基本類型數據。它不會復制對象包含的其他對象的引用。當我們使用淺拷貝創建一個新對象時,它將引用已復制對象的對象,以便指向原始對象。這意味著,如果我們修改任一對象,它將反映在另一個對象中。

public class Person {
private String name;
private Address address;
public Person(String name, Address address) {
this.name = name;
this.address = address;
}
// Shallow copy constructor
public Person(Person person) {
this.name = person.name;
this.address = person.address;
}
}
public class Address {
private String city;
private String state;
public Address(String city, String state) {
this.city = city;
this.state = state;
}
}
public class Main {
public static void main(String[] args) {
Address address = new Address("Washington DC", "DC");
Person person1 = new Person("John", address);
Person person2 = new Person(person1);
person2.getAddress().setCity("New York"); // This should only change person2's address, not person1's
}
}

深復制是指復制對象以及其中包含的對象。深復制創建一個新對象,它將復制所有包含在原始對象中的對象。當我們使用深拷貝創建一個新對象時,它會創建一個新的對象來確保無論我們修改哪個對象,它不會影響副本或原始對象。

public class Person {
private String name;
private Address address;
public Person(String name, Address address) {
this.name = name;
this.address = address;
}
// Deep copy constructor
public Person(Person person) {
this.name = person.name;
this.address = new Address(person.getAddress().getCity(), person.getAddress().getState());
}
}
public class Address {
private String city;
private String state;
public Address(String city, String state) {
this.city = city;
this.state = state;
}
// Getter and Setter methods
}
public class Main {
public static void main(String[] args) {
Address address = new Address("Washington DC", "DC");
Person person1 = new Person("John", address);
Person person2 = new Person(person1);
person2.getAddress().setCity("New York"); // This should only change person2's address, not person1's
}
}

總之,當我們需要復制對象時,淺復制和深復制是兩種常用的方法。當我們只需對對象本身進行更改時,淺復制可能更加適合。但是,如果我們需要更改類中的對象或引用,則深復制可能是更好的選擇。