通过序列化举办深层复制(java)
若研究一下第10章先容的谁人Java 1.1工具序列化示例,大概发明若在一个工具序列化今后再除掉对它的序列化,可能说举办装配,那么实际经验的正是一个“克隆”的进程。
那么为什么不消序列化举办深层复制呢?下面这个例子通过计较执行时间比拟了这两种要领:
//: Compete.java import java.io.*; class Thing1 implements Serializable {} class Thing2 implements Serializable { Thing1 o1 = new Thing1(); } class Thing3 implements Cloneable { public Object clone() { Object o = null; try { o = super.clone(); } catch (CloneNotSupportedException e) { System.out.println("Thing3 can't clone"); } return o; } } class Thing4 implements Cloneable { Thing3 o3 = new Thing3(); public Object clone() { Thing4 o = null; try { o = (Thing4)super.clone(); } catch (CloneNotSupportedException e) { System.out.println("Thing4 can't clone"); } // Clone the field, too: o.o3 = (Thing3)o3.clone(); return o; } } public class Compete { static final int SIZE = 5000; public static void main(String[] args) { Thing2[] a = new Thing2[SIZE]; for(int i = 0; i < a.length; i++) a[i] = new Thing2(); Thing4[] b = new Thing4[SIZE]; for(int i = 0; i < b.length; i++) b[i] = new Thing4(); try { long t1 = System.currentTimeMillis(); ByteArrayOutputStream buf = new ByteArrayOutputStream(); ObjectOutputStream o = new ObjectOutputStream(buf); for(int i = 0; i < a.length; i++) o.writeObject(a[i]); // Now get copies: ObjectInputStream in = new ObjectInputStream( new ByteArrayInputStream( buf.toByteArray())); Thing2[] c = new Thing2[SIZE]; for(int i = 0; i < c.length; i++) c[i] = (Thing2)in.readObject(); long t2 = System.currentTimeMillis(); System.out.println( "Duplication via serialization: " + (t2 - t1) + " Milliseconds"); // Now try cloning: t1 = System.currentTimeMillis(); Thing4[] d = new Thing4[SIZE]; for(int i = 0; i < d.length; i++) d[i] = (Thing4)b[i].clone(); t2 = System.currentTimeMillis(); System.out.println( "Duplication via cloning: " + (t2 - t1) + " Milliseconds"); } catch(Exception e) { e.printStackTrace(); } } } ///:~
个中,Thing2和Thing4包括了成员工具,所以需要举办一些深层复制。一个有趣的处所是尽量Serializable类很容易配置,但在复制它们时却要做多得多的事情。克隆涉及到大量的类配置事情,但实际的工具复制是相当简朴的。功效很好地说明白一切。下面是屡次运行别离获得的功效:
简直
Duplication via serialization: 3400 Milliseconds Duplication via cloning: 110 Milliseconds Duplication via serialization: 3410 Milliseconds Duplication via cloning: 110 Milliseconds Duplication via serialization: 3520 Milliseconds Duplication via cloning: 110 Milliseconds
除了序列化和克隆之间庞大的时间差别以外,我们也留意到序列化技能的运行功效并不不变,而克隆每一次耗费的时间都是沟通的。