一、Int3自Int2继承而来,将Int2的clone()当做Int3的clone()调用时,它会调用Object.clone(),判断出当前操作的是Int3,并复制Int3内的所有二进制位,只要没有新增需要克隆的句柄,对Object.clone()的一个调用就能完成所有必要的复制,可以总结出对Vector进行深层复制的先决条件:在克隆了Vector后,必须在其中遍历,并克隆由Vector指向的每个字段,为了对HashTable进行深层复制,也必须采取类似的处理,在克隆了对象以后,可以自由的改变他,而原来的那个对象不受影响。
import java.util.Enumeration;
import java.util.Vector;}
结果:
x = 10 , x2 = 11
x3 = 7 , x4 = 7
v = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
v: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
v2: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
二、通过序列化进行深层复制,对象在序列化后再撤销对它的序列化,那么实际经历的正是一个”克隆”过程,但花费时间远远大于克隆
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
class Thing1 implements Serializable{}
class Thing2 implements Serializable{
Thing1 o1 = new Thing1();
}
class Thing3 implements Cloneable{
public Object clone() throws CloneNotSupportedException{
Object o = null;
o=super.clone();
return o;
}
}
class Thing4 implements Cloneable{
Thing3 o3 = new Thing3();
public Object clone() throws CloneNotSupportedException{
Thing4 o = null;
o = (Thing4)super.clone();
o.o3 = (Thing3)o3.clone();
return o;
}
}
public class Compete {
static final int SIZE = 5000;
public static void main(String[] args) throws IOException, ClassNotFoundException, CloneNotSupportedException {
Thing2[] a = new Thing2[SIZE];
for(int i=0; i
}
Thing4[] b = new Thing4[SIZE];
for(int i=0; i
}
long t1 = System.nanoTime();
ByteArrayOutputStream bout = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(bout);
for(int i=0; i
}
ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bout.toByteArray()));
Thing2[] c = new Thing2[SIZE];
for(int i=0; i
}
long t2 = System.nanoTime();
System.out.println("Duplication via serialization : " + (t2-t1) + " nanoTime");
t1= System.nanoTime();
Thing4[] d = new Thing4[SIZE];
for(int i=0; i
}
t2 = System.nanoTime();
System.out.println("Duplication via cloneing : " + (t2-t1) + " nanoTime");
}
}
结果:
Duplication via serialization : 34245163 Milliseconds
Duplication via cloneing : 1400956 Milliseconds