java对象复制
Java对象复制可以通过以下几种方式实现:
- 浅拷贝(Shallow Copy):使用默认的clone()方法实现对象的复制。这种方式只复制对象的基本数据类型的值和对象的引用,而不会复制对象的引用所指向的对象。因此,修改原始对象中的引用对象会影响到复制对象中的引用对象。
class Person implements Cloneable {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
Person person1 = new Person("John", 25);
Person person2 = (Person) person1.clone();
- 深拷贝(Deep Copy):通过自定义的clone()方法实现对象的复制,并在该方法中递归复制引用对象。这样,复制对象中的引用对象与原始对象中的引用对象是彼此独立的,修改原始对象中的引用对象不会影响到复制对象中的引用对象。
class Person implements Cloneable {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public Object clone() throws CloneNotSupportedException {
Person clone = (Person) super.clone();
// 对引用对象进行深拷贝
clone.name = new String(this.name);
return clone;
}
}
Person person1 = new Person("John", 25);
Person person2 = (Person) person1.clone();
- 序列化与反序列化:使用Java的序列化与反序列化机制,将对象写入到流中,然后再从流中读取出来,实现对象的复制。
import java.io.*;
class Person implements Serializable {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public Object 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 ois.readObject();
}
}
Person person1 = new Person("John", 25);
Person person2 = (Person) person1.deepCopy();
``
原文地址: http://www.cveoy.top/t/topic/iTfU 著作权归作者所有。请勿转载和采集!