Javaクローン学習の一例分析


package aboutclone;
/**
 * JAVA      (     《JAVA    》)
 * NOTES:
 * 		       (     Char c)    ,   (   Snake next)     ( HashMap,ArrayList )    .
 * 		                        (   Snake next)        .
 */
public class Snake implements Cloneable {
	  private Snake next;
	  private char c;
	  // Value of i == number of segments
	  Snake(int i, char x) {
	    c = x;
	    if(--i > 0)
	      next = new Snake(i, (char)(x + 1));
	  }
	  void increment() {
	    c++;
	    if(next != null)
	      next.increment();
	  }
	  public String toString() {
	    String s = ":" + c;
	    if(next != null)
	      s += next.toString();
	    return s;
	  }
	  public Object clone() {
	    Object o = null;
	    try {
	      o = super.clone();
	    } catch (CloneNotSupportedException e) {}
	    return o;
	  }
	  public static void main(String[] args) {
	    Snake s = new Snake(5, 'a');
	    System.out.println("s = " + s);
	    Snake s2 = (Snake)s.clone();
	    System.out.println("s2 = " + s2);
	    
	    System.out.print("s2==s ? ");
	    System.out.println(s2==s);		//false,        Char,         Char  ,
	    								//        Snake       ,           .
	    
	    System.out.print("s2.c==s.c ? ");
	    System.out.println(s2.c==s.c);//          Char c ,   'a',   true
	    System.out.print("s2.next==s.next ? ");
	    System.out.println(s2.next==s.next);//           Snake,      ,         ,   true
	    
	    s.increment();
	    System.out.println("after s.increment");
	    
	    System.out.print("s2.c==s.c ? ");
	    System.out.println(s2.c==s.c);	//false, s2.c=='a' , s.c=='b'
	    
	    System.out.print("s2.next==s.next ? ");
	    System.out.println(s2.next==s.next);	//true ,    ,        
	    
	    System.out.println(
	      "after s.increment, s2 = " + s2);
	    System.out.println(
	  	  "after s.increment, s = " + s);
	  }
	}

出力は次のとおりです.

s = :a:b:c:d:e
s2 = :a:b:c:d:e
s2==s ? false
s2.c==s.c ? true
s2.next==s.next ? true
after s.increment
s2.c==s.c ? false
s2.next==s.next ? true
after s.increment, s2 = :a:c:d:e:f
after s.increment, s = :b:c:d:e:f