在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 + '}';
}
}
}
以上是两种常见的实现深拷贝的方式,开发者可以根据实际情况选择合适的方式来实现深拷贝。