Java浅拷贝和深拷贝简单示例
原创约 489 字大约 2 分钟...
Java浅拷贝和深拷贝简单示例
注意
本博文仅供学术研究和交流参考,严禁将其用于商业用途。如因违规使用产生的任何法律问题,使用者需自行负责。
Java中也有浅拷贝和深拷贝的概念。 Java中的对象赋值操作(=)和Object.clone()方法都是浅拷贝, 而使用序列化和反序列化实现对象复制则可以实现深拷贝。
- 浅拷贝示例:
public class Person implements Cloneable {
public String name;
public int age;
public Address address;
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
public class Address {
public String city;
public String country;
}
public class Main {
public static void main(String[] args) throws CloneNotSupportedException {
Person p1 = new Person();
p1.name = "Alice";
p1.age = 25;
p1.address = new Address();
p1.address.city = "Shanghai";
p1.address.country = "China";
Person p2 = (Person) p1.clone();
p1.name = "Bob";
p1.address.city = "Beijing";
System.out.println(p2.name); // Alice
System.out.println(p2.address.city); // Beijing
}
}
在上面的示例中,p1和p2是浅拷贝关系,当我们修改p1的属性值时,p2中相应的属性值也会发生变化。
- 深拷贝示例:
public class Person implements Serializable {
public String name;
public int age;
public Address address;
public Person deepCopy() throws IOException, ClassNotFoundException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(this);
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bais);
return (Person) ois.readObject();
}
}
public class Address implements Serializable {
public String city;
public String country;
}
public class Main {
public static void main(String[] args) throws IOException, ClassNotFoundException {
Person p1 = new Person();
p1.name = "Alice";
p1.age = 25;
p1.address = new Address();
p1.address.city = "Shanghai";
p1.address.country = "China";
Person p2 = p1.deepCopy();
p1.name = "Bob";
p1.address.city = "Beijing";
System.out.println(p2.name); // Alice
System.out.println(p2.address.city); // Shanghai
}
}
在上面的示例中,我们通过序列化和反序列化实现了深拷贝, 当我们修改p1的属性值时,p2中相应的属性值并不会发生变化。
分割线
相关信息
以上就是我关于 Java浅拷贝和深拷贝简单示例 知识点的整理与总结的全部内容,希望对你有帮助。。。。。。。
Powered by Waline v2.15.4