forked from shijiebei2009/Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDeepClone.java
More file actions
79 lines (69 loc) · 2.14 KB
/
Copy pathDeepClone.java
File metadata and controls
79 lines (69 loc) · 2.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package cn.codepub.patterns.core;
import java.io.*;
import java.util.Hashtable;
/**
* <p>
* Created with IntelliJ IDEA. 2015/11/8 21:43
* </p>
* <p>
* ClassName:DeepClone
* </p>
* <p>
* Description:implements a deep clone for yourself
* </P>
*
* @author Wang Xu
* @version V1.0.0
* @since V1.0.0
*/
public class DeepClone {
public static void main(String[] args) {
MyPerson son = new MyPerson("son", 1);
MyPerson myPerson = new MyPerson("father", 11);
myPerson.son = son;
try {
MyPerson deepClone = (MyPerson) myPerson.deepClone();
//修改原值
myPerson.son.name = "newSon";
//可以看到完成了深拷贝,拷贝的引用变量son的name属性并未更改
System.out.println(deepClone.son.name);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
class MyPerson implements Cloneable, Serializable {
public String name;
public int age;
public MyPerson son;
public MyPerson(String name, int age) {
this.name = name;
this.age = age;
}
public MyPerson(String name, int age, MyPerson son) {
this(name, age);
this.son = son;
}
public Object deepClone() throws IOException, ClassNotFoundException {
ByteArrayOutputStream bo = new ByteArrayOutputStream();
ObjectOutputStream oo = new ObjectOutputStream(bo);
oo.writeObject(this);
ByteArrayInputStream bi = new ByteArrayInputStream(bo.toByteArray());
ObjectInputStream oi = new ObjectInputStream(bi);
return oi.readObject();
}
Hashtable hashtable = new Hashtable();
@Override
protected Object clone() throws CloneNotSupportedException {
MyPerson myPerson = null;
try {
myPerson = (MyPerson) super.clone();
myPerson.son = (MyPerson) son.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return myPerson;
}
}