public class Snake implements Cloneable{
private Snake next;
private char c;
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);
s.increment();
System.out.println("after s.increment, s2 = " +s2);
}
}
朋友们讲一下这个程序,小弟没有搞懂!

解决方案 »

  1.   

    java.lang.object的clone()是浅拷贝
    要深拷贝需要自己写把clone写成下面这样就深拷贝了:
    public Object clone(){
        Object o = null;
        try{
        o = super.clone();  
        if (this.next != null){
        ((Snake)o).next = (Snake)this.next.clone();}    }catch(CloneNotSupportedException e){}
        return o;   
        }
      

  2.   


    你的深克隆是可以,可是当有N多个引用类型就不好了 代码要写很多 我介绍一个简单的深克隆啊:
    public Object deepClone() throws Exception
    {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(bos);
    oos.writeObject(this); ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
    ObjectInputStream ois = new ObjectInputStream(bis);
    return ois.readObject();
    }