淺拷貝 vs 深拷貝
| 類型 | 行為 | 引用型別欄位 |
| 淺拷貝 | 複製基本型別值、複製引用地址 | 新舊物件共享同一引用物件 |
| 深拷貝 | 基本型別值複製、引用型別遞歸新建 | 新舊物件擁有獨立的引用物件副本 |
方式一:實作 Cloneable + 遞歸 clone()
步驟
- 實作
Cloneable 介面(標記介面)。
- 覆寫
clone() 為 public。
- 呼叫
super.clone() 取得淺拷貝。
- 手動對引用型別欄位呼叫
clone()。
代碼範例
class Professor implements Cloneable {
String name; int age;
Professor(String name, int age){ this.name=name; this.age=age; }
public Object clone() {
try { return super.clone(); }
catch (CloneNotSupportedException e) { throw new AssertionError(e); }
}
}
class Student implements Cloneable {
String name; int age; Professor p;
Student(String name, int age, Professor p){ this.name=name; this.age=age; this.p=p; }
public Object clone() {
Student s = (Student) super.clone(); // 淺拷貝
s.p = (Professor) p.clone(); // 深拷貝教授物件
return s;
}
}
// 測試
Professor p = new Professor("Wang", 50);
Student s1 = new Student("Zhang", 18, p);
Student s2 = (Student) s1.clone();
s2.p.name = "Li"; s2.p.age = 30;
System.out.println(s1.p.name); // "Wang" —— 未受影響,深拷貝成功
方式二:序列化(Serialization)深拷貝
將物件寫入位元組流再讀出,自動遞歸複製整個物件圖。
前提條件
- 所有需拷貝的類別必須實作
Serializable。
- 不可序列化的欄位(如
Thread、Socket、Connection)需標記 transient 並自行處理。
通用工具方法
public static T deepClone(T obj) {
try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos)) {
oos.writeObject(obj);
try (ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bis)) {
return (T) ois.readObject();
}
} catch (IOException | ClassNotFoundException e) {
throw new RuntimeException("深拷貝失敗", e);
}
}
使用範例
class Professor implements Serializable { String name; int age; /* ... */ }
class Student implements Serializable { String name; int age; Professor p; /* ... */ }
Professor p = new Professor("Wang", 50);
Student s1 = new Student("Zhang", 18, p);
Student s2 = deepClone(s1); // 一行搞定深拷貝
s2.p.name = "Li";
System.out.println(s1.p.name); // "Wang"
兩種方式比較
| 維度 | Cloneable + 手動 clone | 序列化 |
| 效能 | 高(無 IO、反射開銷) | 較低(序列化/反序列化開銷大) |
| 程式碼量 | 每個類別需手寫 clone 邏輯 | 通用工具一次寫好,類別只需 implements Serializable |
| 對複雜物件圖支援 | 需手動遞歸處理每個引用 | 自動遞歸整個物件圖 |
| 不可序列化欄位處理 | 自然處理(直接複製引用或自行 new) | 需標記 transient + 額外邏輯恢復 |
| 建構子呼叫 | 不呼叫建構子 | 不呼叫建構子(透過反射分配記憶體) |
現代替代方案
- Jackson / Gson:
gson.fromJson(gson.toJson(obj), clazz) — 簡單、效能尚可、自動處理循環引用(需設定)。
- MapStruct / ModelMapper — 映射庫,適用於 DTO 轉換而非純深拷貝。
- Java Records (Java 16+) — 不可變資料載體,天生無需深拷貝;需修改時用
with 方法產生新實例。
選型建議
- 高效能、物件結構固定、引用層級淺 → Cloneable。
- 物件圖複雜、頻繁變動、不想維護 clone 代碼 → 序列化工具法 或 JSON 往復。
- 新專案優先考慮 Immutable 設計 + Record 避免拷貝需求。