如何进行Java对象的克隆
1个回答
展开全部
以数组对象的克隆为例。
Java程序:
public class Main {
public static void main(String[] args) {
int[] a = {1, 2, 3};
int[] b = a.clone(); //b是a的克隆,a和b指向不同的数组
int[] c = a; //c是a的引用,a和c指向同一个数组
a[0] = 10;
System.out.println("a[0] = " + a[0]);
System.out.println("b[0] = " + b[0]);
System.out.println("c[0] = " + c[0]);
}
}
运行测试:
a[0] = 10
b[0] = 1
c[0] = 10
自定义类的情况如下:
public class Main {
public static void main(String[] args) {
A a1 = new A();
a1.name = "Smith";
A a2 = a1;
A a3 = (A) a1.clone();
a1.name = "White";
System.out.println("a1 : " + a1.name);
System.out.println("a2 : " + a2.name);
System.out.println("a3 : " + a3.name);
}
}
class A implements Cloneable {
public String name = null;
@Override
public Object clone() {
A a = null;
try{
a = (A)super.clone();
}
catch(CloneNotSupportedException e) {
e.printStackTrace();
}
return a;
}
}
运行测试:
a1 : White
a2 : White
a3 : Smith
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询