Source of Compete.java


  1: //: appendixa:Compete.java
  2: // From 'Thinking in Java, 2nd ed.' by Bruce Eckel
  3: // www.BruceEckel.com. See copyright notice in CopyRight.txt.
  4: import java.io.*;

  6: class Thing1 implements Serializable {}
  7: class Thing2 implements Serializable {
  8:   Thing1 o1 = new Thing1();
  9: }

 11: class Thing3 implements Cloneable {
 12:   public Object clone() {
 13:     Object o = null;
 14:     try {
 15:       o = super.clone();
 16:     } catch(CloneNotSupportedException e) {
 17:       System.err.println("Thing3 can't clone");
 18:     }
 19:     return o;
 20:   }
 21: }

 23: class Thing4 implements Cloneable {
 24:   Thing3 o3 = new Thing3();
 25:   public Object clone() {
 26:     Thing4 o = null;
 27:     try {
 28:       o = (Thing4)super.clone();
 29:     } catch(CloneNotSupportedException e) {
 30:       System.err.println("Thing4 can't clone");
 31:     }
 32:     // Clone the field, too:
 33:     o.o3 = (Thing3)o3.clone();
 34:     return o;
 35:   }
 36: }

 38: public class Compete {
 39:   static final int SIZE = 5000;
 40:   public static void main(String[] args) 
 41:   throws Exception {
 42:     Thing2[] a = new Thing2[SIZE];
 43:     for(int i = 0; i < a.length; i++)
 44:       a[i] = new Thing2();
 45:     Thing4[] b = new Thing4[SIZE];
 46:     for(int i = 0; i < b.length; i++)
 47:       b[i] = new Thing4();
 48:     long t1 = System.currentTimeMillis();
 49:     ByteArrayOutputStream buf = 
 50:       new ByteArrayOutputStream();
 51:     ObjectOutputStream o =
 52:       new ObjectOutputStream(buf);
 53:     for(int i = 0; i < a.length; i++)
 54:       o.writeObject(a[i]);
 55:     // Now get copies:
 56:     ObjectInputStream in =
 57:       new ObjectInputStream(
 58:         new ByteArrayInputStream(
 59:           buf.toByteArray()));
 60:     Thing2[] c = new Thing2[SIZE];
 61:     for(int i = 0; i < c.length; i++)
 62:       c[i] = (Thing2)in.readObject();
 63:     long t2 = System.currentTimeMillis();
 64:     System.out.println(
 65:       "Duplication via serialization: " +
 66:       (t2 - t1) + " Milliseconds");
 67:     // Now try cloning:
 68:     t1 = System.currentTimeMillis();
 69:     Thing4[] d = new Thing4[SIZE];
 70:     for(int i = 0; i < d.length; i++)
 71:       d[i] = (Thing4)b[i].clone();
 72:     t2 = System.currentTimeMillis();
 73:     System.out.println(
 74:       "Duplication via cloning: " +
 75:       (t2 - t1) + " Milliseconds");
 76:   }
 77: } ///:~