Object类中提供了clone方法.
import java.util.ArrayList;
public class TestClone implements Cloneable {
public TestClone() {
System.out.println("构造函数被执行了...");
}
private ArrayList<String> arrayList = new ArrayList<String>();
@Override
public TestClone clone() {
TestClone thing = null;
try {
thing = (TestClone) super.clone();
//,Object 类提供的方法clone 只是拷贝本对象,
其对象内部的数组、引用对象等都不拷贝,还是指向原生对象的内部元素地址,这种拷贝就叫做浅拷贝,仅会对基本类型包括String,实现拷贝.如果要拷贝内部对象应该用以下这样实现了深拷贝:
thing.arrayList = (ArrayList<String>) this.arrayList.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return thing;
}
public void setValue(String value) {
this.arrayList.add(value);
}
public ArrayList<String> getValue() {
return this.arrayList;
}
public static void main(String[] args) {
// 产生一个对象
TestClone thing = new TestClone();
thing.setValue("张三");
// 拷贝一个对象
TestClone t = thing.clone();
t.setValue("李四");
System.out.println(thing.getValue());
}
}