下面,图老师小编带您去了解一下Java Clone(类的复制)实例代码,生活就是不断的发现新事物,get新技能~
【 tulaoshi.com - 编程语言 】
自己实现了一遍:
(本文来源于图老师网站,更多请访问http://www.tulaoshi.com/bianchengyuyan/)代码如下:
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 VectorB claB;
public A(){
name=new String[2];
claB=new VectorB();
}
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 VectorB();//将clone进行到底
for(int i=0;iclaB.size();i++){
B temp=(B)claB.get(i).clone();//当然Class B也要实现相应clone方法
o.claB.add(temp);
}
return o;
}
}
来源:http://www.tulaoshi.com/n/20160219/1596518.html
看过《Java Clone(类的复制)实例代码》的人还看了以下文章 更多>>