在Java中,實現深拷貝可以通過以下幾種方式:
import java.io.*;
public class DeepCopyExample {
public static void main(String[] args) throws Exception {
// 創建原始對象
Person person = new Person("Alice", 25);
// 深拷貝
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(person);
oos.close();
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bis);
Person copiedPerson = (Person) ois.readObject();
ois.close();
// 輸出兩個對象的信息,驗證是否是深拷貝
System.out.println("原始對象:" + person);
System.out.println("拷貝對象:" + copiedPerson);
}
static class Person implements Serializable {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Person{name='" + name + "', age=" + age + '}';
}
}
}
public class DeepCopyExample {
public static void main(String[] args) throws CloneNotSupportedException {
// 創建原始對象
Person person = new Person("Alice", 25);
// 深拷貝
Person copiedPerson = (Person) person.clone();
// 輸出兩個對象的信息,驗證是否是深拷貝
System.out.println("原始對象:" + person);
System.out.println("拷貝對象:" + copiedPerson);
}
static class Person implements Cloneable {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
protected Object clone() throws CloneNotSupportedException {
Person clonedPerson = (Person) super.clone();
return clonedPerson;
}
@Override
public String toString() {
return "Person{name='" + name + "', age=" + age + '}';
}
}
}
以上是兩種常見的實現深拷貝的方式,開發者可以根據實際情況選擇合適的方式來實現深拷貝。