关于clone()方法的两个问题
public class TestClone implements Cloneable{
int count;
TestClone next;
public TestClone(int count)
{
this.count=count;
if(count>0)
next=new TestClone(count-1);
}
void add()
{
count++;
if(next!=null)
next.count++;
}
public String toString()
{
String s=String.valueOf(count)+" ";
if(next!=null)
s+=next.toString();
return s;
}
public Object clone()
{
Object o=null;
//如果没有实现cloneable,将会抛出CloneNotSupported异常
try
{
o=super.clone();
}
catch(CloneNotSupportedException e)
{
System.err.println("cannot clone");
}
return o;
}
public static void main(String[] args)
{
TestClone c=new TestClone(5);
System.out.println("c="+c);
TestClone c1=(TestClone)c.clone();
System.out.println("c1="+c1);
c.add();
System.out.println("after added\nc="+c+"\nc1="+c1);
}
}
其中TestClone c1=(TestClone)c.clone();是什么意思?
还有执行c.add()语句后,为什么输出的是c=6 5 3 2 1 c1=5 5 3 2 1?