Java Clone(類的復(fù)制)實(shí)例代碼
自己實(shí)現(xiàn)了一遍:
public class A implements Cloneable {
public String str[];
A() {
str = new String[2];
}
public Object clone() {
A o = null;
try {
o = (A) super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
o.str = new String[2];
return o;
}
}
void run() throws Exception {
A a1 = new A(), a2 = new A();
a1.str[0] = "a"; a1.str[1] = "b";
a2 = (A) a1.clone();
a2.str[0] = "c"; a2.str[1] = "d";
System.out.println(a1.str[0] + " " + a2.str[0]);
}
結(jié)果:
a c
1.
public class A implements Cloneable {
public String name;
public Object clone() {
A o = null;
try {
o = (A) super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return o;
}
}
2.
public class A implements Cloneable {
public String name[];
public A(){
name=new String[2];
}
public Object clone() {
A o = null;
try {
o = (A) super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return o;
}
}
3.
public class A implements Cloneable {
public String name[];
public Vector<B> claB;
public A(){
name=new String[2];
claB=new Vector<B>();
}
public Object clone() {
A o = null;
try {
o = (A) super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
o.name=new String[2];//深度clone
o.claB=new Vector<B>();//將clone進(jìn)行到底
for(int i=0;i<claB.size();i++){
B temp=(B)claB.get(i).clone();//當(dāng)然Class B也要實(shí)現(xiàn)相應(yīng)clone方法
o.claB.add(temp);
}
return o;
}
}
相關(guān)文章
Java 數(shù)據(jù)結(jié)構(gòu)之刪除鏈表中重復(fù)的結(jié)點(diǎn)
在一個(gè)排序的鏈表中,會存在重復(fù)的結(jié)點(diǎn),如何實(shí)現(xiàn)刪除該鏈表中重復(fù)的結(jié)點(diǎn),重復(fù)的結(jié)點(diǎn)不保留,并返回鏈表頭指針呢?接下來小編將帶你詳細(xì)介紹2021-12-12Spring Boot Logging Level設(shè)置為off時(shí)的Bug
這篇文章主要介紹了Spring Boot Logging Level設(shè)置為off時(shí)的Bug,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-09-09jeefast和Mybatis實(shí)現(xiàn)三級聯(lián)動(dòng)的示例代碼
這篇文章主要介紹了jeefast和Mybatis實(shí)現(xiàn)三級聯(lián)動(dòng)的示例代碼,代碼簡單易懂,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-10-10Tomcat數(shù)據(jù)源配置方法_JBuilder中
今天幫一同事配置一個(gè)數(shù)據(jù)源,采用tomcat5.5.9,本來是個(gè)很簡單的事,以前也配過,但由于很長時(shí)間沒用過容器提供的數(shù)據(jù)源了(IOC用慣了),也只記的個(gè)大概了,所以剛開始一配就出錯(cuò)了,google了一下,有很多資料,照著試試卻都不好使(到不是別人說的不對,只是大家用的版本不同)。2008-10-10Java切面(Aspect)的多種實(shí)現(xiàn)方式
這篇文章主要給大家介紹了關(guān)于Java切面(Aspect)的多種實(shí)現(xiàn)方式,在Java開發(fā)中切面(Aspect)是一種常用的編程方式,用于實(shí)現(xiàn)橫切關(guān)注點(diǎn)(cross-cutting concern),需要的朋友可以參考下2023-08-08