Java深拷贝代码示例
时间: 2023-07-08 19:39:12 浏览: 102
Java中的深拷贝(深复制)和浅拷贝(浅复制) 示例代码
5星 · 资源好评率100%
Java深拷贝可以使用序列化来实现,下面是示例代码:
```java
import java.io.*;
public class DeepCopy implements Serializable {
private int value;
private DeepCopyObj obj;
public DeepCopy(int value, DeepCopyObj obj) {
this.value = value;
this.obj = obj;
}
public DeepCopy deepCopy() throws IOException, ClassNotFoundException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(this);
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bis);
return (DeepCopy) ois.readObject();
}
public static void main(String[] args) throws IOException, ClassNotFoundException {
DeepCopyObj obj = new DeepCopyObj(1, "obj");
DeepCopy deepCopy = new DeepCopy(2, obj);
DeepCopy deepCopy2 = deepCopy.deepCopy();
System.out.println(deepCopy == deepCopy2); // false
System.out.println(deepCopy.obj == deepCopy2.obj); // false
}
}
class DeepCopyObj implements Serializable {
private int value;
private String name;
public DeepCopyObj(int value, String name) {
this.value = value;
this.name = name;
}
}
```
以上代码中,我们使用了Java的序列化机制实现了对象的深拷贝。实现方式是将对象序列化为一个字节数组,然后再将其反序列化为一个新的对象。需要注意的是,被拷贝对象及其属性都需要实现Serializable接口。
阅读全文