1、表层克隆
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));
}
}
public 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);
s2.increment();
system.out.println("after s2.increment, s="+s+" s2 ="+s2);
}
}
此时的输出结果:
s =:a:b:c:d:e
s2 =:a:b:c:d:e
after s2.increment, s=:a:c:d:e:f s2 =:b:c:d:e:f
2、深层克隆
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));
}
}
public 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(){
snake o = null;
try{
o = (snake)super.clone();
}catch(clonenotsupportedexception e){}
if(o.next !=null)
o.next = (snake)o.next.clone();
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);
s2.increment();
system.out.println("after s2.increment, s="+s);
system.out.println("s2 ="+s2);
}
}
此时的输出结果为:
s =:a:b:c:d:e
s2 =:a:b:c:d:e
after s2.increment, s=:a:b:c:d:e s2 =:b:c:d:e:f
总结:
在colne()函数中,如果只是简单的调用一下父类的super.clone()则只是将当前类的基
本类型按位复制,克隆后的类所含有的对象句柄仍然和当前类相同。所以,如果需要进行深
层克隆,则需要在调用super.clone()之后,克隆该类含有的对象类。
闽公网安备 35060202000074号