对象的克隆(clone方法)

1.深拷贝与浅拷贝

浅拷贝是指拷贝对象时仅仅拷贝对象本身(包括对象中的基本变量),而不拷贝对象包含的引用指向的对象。深拷贝不仅拷贝对象本身,而且拷贝对象包含的引用指向的所有对象。

2.深拷贝和浅拷贝的实现

浅拷贝的实现很简单,直接继承Object类的clone方法就是浅拷贝

现在说一下深拷贝,深拷贝一般的做法是把类实现Serializable接口,使得这个类具有序列化特性

然后提供深拷贝的方法,先把整个对象序列化到流里,然后再从流里反序列化出来

代码如下

 1 package test;
 2 
 3 import java.io.*;
 4 
 5 public class DeepCopyTest {
 6 
 7     public static void main(String[] args) throws Exception,
 8             IOException, ClassNotFoundException {
 9         long t1 = System.currentTimeMillis();
10         Professor2 p = new Professor2("wangwu", 50);
11         Student2 s1 = new Student2("zhangsan", 18, p);
12         Student2 s2 = (Student2) s1.deepClone();
13         s2.p.name = "lisi";
14         s2.p.age = 30;
15         System.out.println("name=" + s1.p.name + "," + "age=" + s1.p.age); // 学生1的教授不改变。
16         long t2 = System.currentTimeMillis();
17         System.out.println(t2-t1);
18     }
19 
20 }
21 
22 class Professor2 implements Serializable {
23     private static final long serialVersionUID = 1L;
24     String name;
25     int age;
26 
27     Professor2(String name, int age) {
28         this.name = name;
29         this.age = age;
30     }
31 }
32 
33 class Student2 implements Serializable {
34     private static final long serialVersionUID = 1L;
35     String name;// 常量对象。
36     int age;
37     Professor2 p;// 学生1和学生2的引用值都是一样的。
38 
39     Student2(String name, int age, Professor2 p) {
40         this.name = name;
41         this.age = age;
42         this.p = p;
43     }
44 
45     public Object deepClone() throws Exception {
46         // 将对象写到流里
47         ByteArrayOutputStream bo = new ByteArrayOutputStream();
48         ObjectOutputStream oo = new ObjectOutputStream(bo);
49         oo.writeObject(this);
50         // 从流里读出来
51         ByteArrayInputStream bi = new ByteArrayInputStream(bo.toByteArray());
52         ObjectInputStream oi = new ObjectInputStream(bi);
53         return (oi.readObject());
54     }
55 
56 }
 
原文地址:https://www.cnblogs.com/billmiao/p/9872185.html