标题:关于clone()方法的两个问题
取消只看楼主
独孤客
Rank: 1
等 级:新手上路
帖 子:48
专家分:0
注 册:2006-5-1
 问题点数:0 回复次数:3 
关于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 
2006-11-02 21:19
独孤客
Rank: 1
等 级:新手上路
帖 子:48
专家分:0
注 册:2006-5-1
得分:0 
还忘了一个。在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又是什么意思?

乘天地之正,御六气之辩,以游于无穷,是为逍遥!!!
2006-11-02 21:27
独孤客
Rank: 1
等 级:新手上路
帖 子:48
专家分:0
注 册:2006-5-1
得分:0 
请教几个比较白痴的问题!
(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却没自加?

乘天地之正,御六气之辩,以游于无穷,是为逍遥!!!
2006-12-04 23:22
独孤客
Rank: 1
等 级:新手上路
帖 子:48
专家分:0
注 册:2006-5-1
得分:0 
明白了,谢谢!

乘天地之正,御六气之辩,以游于无穷,是为逍遥!!!
2006-12-22 22:42



参与讨论请移步原网站贴子:https://bbs.bccn.net/thread-100420-1-1.html




关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.691689 second(s), 8 queries.
Copyright©2004-2025, BCCN.NET, All Rights Reserved