深层克隆

王朝other·作者佚名  2008-05-31
窄屏简体版  字體: |||超大  

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()之后,克隆该类含有的对象类。

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航