国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發(fā)設計 > 正文

深層克隆

2019-11-18 14:47:44
字體:
供稿:網(wǎng)友

  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);
}
}


此時的輸出結(jié)果:
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);
}
}

此時的輸出結(jié)果為:
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

總結(jié):
在colne()函數(shù)中,假如只是簡單的調(diào)用一下父類的super.clone()則只是將當前類的基
本類型按位復制,克隆后的類所含有的對象句柄仍然和當前類相同。所以,假如需要進行深
層克隆,則需要在調(diào)用super.clone()之后,克隆該類含有的對象類。

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 克什克腾旗| 宣城市| 虎林市| 吉安县| 崇阳县| 仁寿县| 瑞安市| 岗巴县| 青浦区| 龙川县| 富顺县| 杭锦旗| 闻喜县| 鄂伦春自治旗| 灵寿县| 南江县| 白沙| 新泰市| 河源市| 东明县| 巴马| 广水市| 南平市| 油尖旺区| 广元市| 延庆县| 长海县| 长宁区| 江北区| 峨眉山市| 砚山县| 浪卡子县| 荥经县| 韶山市| 阿合奇县| 八宿县| 全椒县| 军事| 肇源县| 扎鲁特旗| 东乌|