共計(jì) 1761 個(gè)字符,預(yù)計(jì)需要花費(fèi) 5 分鐘才能閱讀完成。
在 Java 中,可以通過兩種方式來實(shí)現(xiàn)對象克隆:淺拷貝和深拷貝。
- 淺拷貝:使用 Object 類的 clone() 方法進(jìn)行對象的淺拷貝。淺拷貝會創(chuàng)建一個(gè)新的對象,將原始對象的非靜態(tài)字段的值復(fù)制到新對象中,對于引用類型的字段,復(fù)制的是引用而不是對象本身。如果原始對象中的字段是可變的,修改新對象中的字段會影響原始對象,反之亦然。
例如:
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();
}
}
}
- 深拷貝:通過實(shí)現(xiàn) Serializable 接口以及使用序列化和反序列化的方式實(shí)現(xiàn)對象的深拷貝。深拷貝會創(chuàng)建一個(gè)新的對象,將原始對象及其引用的對象都復(fù)制到新對象中,新對象與原始對象是完全獨(dú)立的。
例如:
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();
}
}
}
需要注意的是,要實(shí)現(xiàn)深拷貝,對象及其引用的對象都需要實(shí)現(xiàn) Serializable 接口。
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!
正文完