Source of Cloning.java


  1: //: appendixa:Cloning.java
  2: // From 'Thinking in Java, 2nd ed.' by Bruce Eckel
  3: // www.BruceEckel.com. See copyright notice in CopyRight.txt.
  4: // The clone() operation works for only a few
  5: // items in the standard Java library.
  6: import java.util.*;

  8: class Int {
  9:   private int i;
 10:   public Int(int ii) { i = ii; }
 11:   public void increment() { i++; }
 12:   public String toString() { 
 13:     return Integer.toString(i); 
 14:   }
 15: }

 17: public class Cloning {
 18:   public static void main(String[] args) {
 19:     ArrayList v = new ArrayList();
 20:     for(int i = 0; i < 10; i++ )
 21:       v.add(new Int(i));
 22:     System.out.println("v: " + v);
 23:     ArrayList v2 = (ArrayList)v.clone();
 24:     // Increment all v2's elements:
 25:     for(Iterator e = v2.iterator();
 26:         e.hasNext(); )
 27:       ((Int)e.next()).increment();
 28:     // See if it changed v's elements:
 29:     System.out.println("v: " + v);
 30:   }
 31: } ///:~