Source of AddingClone.java


  1: //: appendixa:AddingClone.java
  2: // From 'Thinking in Java, 2nd ed.' by Bruce Eckel
  3: // www.BruceEckel.com. See copyright notice in CopyRight.txt.
  4: // You must go through a few gyrations
  5: // to add cloning to your own class.
  6: import java.util.*;

  8: class Int2 implements Cloneable {
  9:   private int i;
 10:   public Int2(int ii) { i = ii; }
 11:   public void increment() { i++; }
 12:   public String toString() {
 13:     return Integer.toString(i);
 14:   }
 15:   public Object clone() {
 16:     Object o = null;
 17:     try {
 18:       o = super.clone();
 19:     } catch(CloneNotSupportedException e) {
 20:       System.err.println("Int2 can't clone");
 21:     }
 22:     return o;
 23:   }
 24: }

 26: // Once it's cloneable, inheritance
 27: // doesn't remove cloneability:
 28: class Int3 extends Int2 {
 29:   private int j; // Automatically duplicated
 30:   public Int3(int i) { super(i); }
 31: }

 33: public class AddingClone {
 34:   public static void main(String[] args) {
 35:     Int2 x = new Int2(10);
 36:     Int2 x2 = (Int2)x.clone();
 37:     x2.increment();
 38:     System.out.println(
 39:       "x = " + x + ", x2 = " + x2);
 40:     // Anything inherited is also cloneable:
 41:     Int3 x3 = new Int3(7);
 42:     x3 = (Int3)x3.clone();

 44:     ArrayList v = new ArrayList();
 45:     for(int i = 0; i < 10; i++ )
 46:       v.add(new Int2(i));
 47:     System.out.println("v: " + v);
 48:     ArrayList v2 = (ArrayList)v.clone();
 49:     // Now clone each element:
 50:     for(int i = 0; i < v.size(); i++)
 51:       v2.set(i, ((Int2)v2.get(i)).clone());
 52:     // Increment all v2's elements:
 53:     for(Iterator e = v2.iterator();
 54:         e.hasNext(); )
 55:       ((Int2)e.next()).increment();
 56:     // See if it changed v's elements:
 57:     System.out.println("v: " + v);
 58:     System.out.println("v2: " + v2);
 59:   }
 60: } ///:~