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+i));
}
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()");
System.out.println("s="+s);
System.out.println("s2="+s2);
}
}
------解决思路----------------------
s=:a:e:h:j:k
s2=:a:e:h:j:k
after s.increment()
s=:b:f:i:k:l
s2=:a:f:i:k:l
没有细看楼主的代码,不过楼主的这个克隆方法
public Object clone(){
Object o = null;
try {
o = super.clone();
} catch (CloneNotSupportedException e) {
}
return o;
}
因为 Snake 类中包含对象 Snake 型的属性,所以浅克隆应该会出事的。
基本类型之外的对象类型,都需要使用深克隆