java实现深拷贝的两种方式,写的不准确的地方还请大神指正
1.采用序列化的方式进行深拷贝;
2.依次克隆各个可变的引用类型域的方式实现;
代码如下:
首先构建Teacher类,实现接口,clone方法使用序列化实现:
class Teacher implements Cloneable,Serializable{
/**
*
*/
private static final long serialVersionUID = 4390576177500173601L;
public String name;
public String phone;
public Teacher(String name, String phone) {
this.name = name;
this.phone = phone;
}
@Override
protected Object clone() {
Teacher t = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream b= null;
try {
b = new ObjectOutputStream(baos);
b.writeObject(this);
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
b.close();
} catch (IOException e) {
e.printStackTrace();
}
}
ByteArrayInputStream bi = new ByteArrayInputStream(baos.toByteArray());
try {
ObjectInputStream oi = new ObjectInputStream(bi);
t = (Teacher) oi.readObject();
oi.close();
bi.close();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return t;
}
}
构建Worker类 ,使用克隆引用的方法实现
class Worker implements Cloneable{
public String name;
public String phone;
public Worker(String name, String phone) {
this.name = name;
this.phone = phone;
}
@Override
protected Worker clone(){
Worker worker = null;
try {
worker = (Worker) super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return worker;
}
}
}
写测试:
public class CloneCompare {
public static void main(String[] args) {
Worker w = new Worker("lisi", "123");
Teacher t = new Teacher("wangwu", "123123");
long time1 = System.currentTimeMillis();
for(int a=0;a<10000;a++){
w.clone();
}
System.out.println(System.currentTimeMillis()-time1);
long time2 = System.currentTimeMillis();
for(int a=0;a<10000;a++){
t.clone();
}
System.out.println(System.currentTimeMillis()-time2);
}
}
测试结果如下:
3
615
效率的差别已经是200多倍了,其实对于类内部应用类型不是很多的情况,简单的引克隆是一种最好的选择。