当前位置: 代码迷 >> Java相关 >> 关于clone()方法的两个问题
  详细解决方案

关于clone()方法的两个问题

热度:217   发布时间:2006-11-02 21:19:39.0
关于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?
搜索更多相关的解决方案: clone  

----------------解决方案--------------------------------------------------------
还忘了一个。在TestClone c1=(TestClone)c.clone();
语句后加上c1.next=(TestClone)c.clone();输出……c1=5 5 4 3 2 1 0 affter added ……c1=6 5 5 3 2 1 0
这多出来的5是哪来的。c1.next又是什么意思?
----------------解决方案--------------------------------------------------------
还忘了一个。在TestClone c1=(TestClone)c.clone();表示 c1是c 的拷贝。
----------------解决方案--------------------------------------------------------
请教几个比较白痴的问题!
(1)next.count=4 3 2 1 0在执行了
if(next!=null)
next.count++
代码之后,为什么next.count不是等于5 4 3 2 1?

(2)执行c.add()后,为什么只有c1.next.count自加了,而c1.count却没自加?
----------------解决方案--------------------------------------------------------
TestClone c=new TestClone(5);
这时候C是5 4 3 2 1 0
System.out.println("c="+c);
TestClone c1=(TestClone)c.clone();
这时候C1是和C一样5 4 3 2 1 0
System.out.println("c1="+c1);
c.add();
c.add()后变为6 5 3 2 1 0你应该没疑问吧?
这时候因为c1没有add(),c1是c的copy,所以c1没变,但为什么显示为5 5 3 2 1 0呢?
是因为第一个5是C1本身所以没变,第二个5却是和c里面第二个5是同一个引用,所以在c.add()时候
就发生了改变。
你可以对程序做如下改动来帮你理解这个问题:
public String toString()
{
String s=String.valueOf(count)+"("+this.hashCode()+") ";
if(next!=null)
s+=next.toString();
return s;
}
其他不变。



----------------解决方案--------------------------------------------------------
关键在这一点
System.out.println( c.next==c1.next ); // output true

----------------解决方案--------------------------------------------------------
明白了,谢谢!
----------------解决方案--------------------------------------------------------
  相关解决方案