在Java中,可以通過兩種方式來實現對象克隆:淺拷貝和深拷貝。
例如:
public class MyClass implements Cloneable {
private int intValue;
private String stringValue;
public MyClass(int intValue, String stringValue) {
this.intValue = intValue;
this.stringValue = stringValue;
}
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
public static void main(String[] args) {
MyClass obj1 = new MyClass(10, "Hello");
try {
MyClass obj2 = (MyClass) obj1.clone();
System.out.println(obj1 == obj2); // false
System.out.println(obj1.intValue == obj2.intValue); // true
System.out.println(obj1.stringValue == obj2.stringValue); // true
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
}
}
例如:
import java.io.*;
public class MyClass implements Serializable {
private int intValue;
private String stringValue;
public MyClass(int intValue, String stringValue) {
this.intValue = intValue;
this.stringValue = stringValue;
}
public MyClass deepClone() throws IOException, ClassNotFoundException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(this);
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bis);
return (MyClass) ois.readObject();
}
public static void main(String[] args) {
MyClass obj1 = new MyClass(10, "Hello");
try {
MyClass obj2 = obj1.deepClone();
System.out.println(obj1 == obj2); // false
System.out.println(obj1.intValue == obj2.intValue); // true
System.out.println(obj1.stringValue == obj2.stringValue); // false
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
需要注意的是,要實現深拷貝,對象及其引用的對象都需要實現Serializable接口。