-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPrototype.java
More file actions
61 lines (57 loc) · 1.76 KB
/
Copy pathPrototype.java
File metadata and controls
61 lines (57 loc) · 1.76 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
import java.util.ArrayList;
import java.io.*;
public class Prototype implements Cloneable{
private ArrayList<Integer> list=new ArrayList<Integer>();
public Prototype clone(){
Prototype prototype=null;
try{
prototype=(Prototype)super.clone(); //Object中clone()方法,浅拷贝
prototype.list = (ArrayList) this.list.clone(); //实现ArrayList的深拷贝
}catch(CloneNotSupportedException e){
e.printStackTrace();
}
return prototype;
}
public void showList(){
for(int i=0;i<list.size();i++)
System.out.println("list["+i+"] is "+list.get(i));
}
public void addList(int elem){
list.add(elem);
}
public void doSomething(){
System.out.println("This is a Prototype.");
}
}
/*
//通过序列化二进制流实现拷贝(深拷贝),Object类的clone()方法通过本地方法复制内存中对象
public class Prototype implements Cloneable, Serializable{
//必须实现Serializable接口,否则writeObject抛异常
private ArrayList list=new ArrayList();
public Prototype clone(){
Prototype prototype=null;
try{
//写入当前对象的二进制流
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(this);
// 读出二进制流产生的新对象
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bis);
prototype=(Prototype)ois.readObject();
}catch(IOException | ClassNotFoundException e){
e.printStackTrace();
}
return prototype;
}
public void showList(){
for(int i=0;i<list.size();i++)
System.out.println("list["+i+"] is "+list.get(i));
}
public void addList(int elem){
list.add(elem);
}
public void doSomething(){
System.out.println("This is a Prototype.");
}
} */