Java Clone(类的复制)实例代码

时间:2021-05-20

自己实现了一遍:

复制代码 代码如下:
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]);
}

结果:

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进行到底
for(int i=0;i<claB.size();i++){
B temp=(B)claB.get(i).clone();//当然Class B也要实现相应clone方法
o.claB.add(temp);
}
return o;
}
}

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章