java 深拷贝 DEMO
时间: 2024-07-23 09:00:56 浏览: 54
在 Java 中,深拷贝通常用于创建对象副本,并确保新创建的对象与原对象完全独立,即使原对象有嵌套的对象,它们也不会共享引用。以下是一个简单的深拷贝实现示例,使用序列化反序列化的办法:
```java
import java.io.*;
public class DeepCopyDemo {
private static final String SERIALIZED_FORMAT = "object serialization format";
public static class MyObject {
private int value;
private String nestedObject;
// getters and setters...
@Override
public String toString() {
return "MyObject{" +
"value=" + value +
", nestedObject='" + nestedObject + '\'' +
'}';
}
public MyObject deepCopy() throws IOException, ClassNotFoundException {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
objectOutputStream.writeObject(this);
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
return (MyObject) objectInputStream.readObject();
}
}
public static void main(String[] args) {
try {
MyObject original = new MyObject();
original.value = 42;
original.nestedObject = "Nested Object";
MyObject copied = original.deepCopy();
System.out.println("Original: " + original); // 输出原始对象
System.out.println("Copied: " + copied); // 输出深拷贝后的对象
// 修改原始对象的值不影响拷贝
original.value = 99;
System.out.println("After modifying original: " + original);
System.out.println("Copied after modification: " + copied); // 输出拷贝仍保持初始值
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
```
在这个例子中,`deepCopy()` 方法将 `MyObject` 对象转换为字节流,然后从字节流中重构一个新的对象。这样,新复制的对象拥有与原对象相同的值,但彼此之间是独立的。
阅读全文