複製物件聽起來簡單,但 Java 裡的「複製」有兩種截然不同的語意,搞混了會產生難以追蹤的 bug——改動副本,卻發現原本的物件也跟著變了。
淺拷貝:新物件的基本型別欄位持有相同的值,但所有引用型別的欄位仍然指向原本那批物件。也就是說,只複製外層,內層共用。
深拷貝:除了基本型別,所有引用到的物件也一併複製一份,副本與原物件徹底斷開關係。
clone 方法會產生一份複本並回傳,一般而言它滿足:
① 對任何物件 x,x.clone() != x(複本不是同一個物件)
② 對任何物件 x,x.clone().getClass() == x.getClass()(型別相同)
③ 若 equals() 定義得當,x.clone().equals(x) 應成立
① 呼叫 Object 的 clone() 方法取得複本;② 在子類別中覆寫 clone() 並宣告為 public;③ 覆寫版本中呼叫 super.clone();④ 讓類別實作 Cloneable 介面。
class Student implements Cloneable
{
String name;
int age;
Student(String name, int age)
{
this.name = name;
this.age = age;
}
public Object clone()
{
Object o = null;
try
{
o = (Student) super.clone(); // Object 的 clone 會判斷要複製哪個型別
}
catch (CloneNotSupportedException e)
{
System.out.println(e.toString());
}
return o;
}
}
public static void main(String[] args)
{
Student s1 = new Student("zhangsan", 18);
Student s2 = (Student) s1.clone();
s2.name = "lisi";
s2.age = 20;
System.out.println("name=" + s1.name + ", age=" + s1.age); // 改 s2 不影響 s1
}
為什麼覆寫時一定要呼叫 super.clone()?因為在執行期,Object 的 clone() 會辨識出你實際要複製的物件型別,為它配置記憶體,並把原物件的內容逐欄位搬過去。少了這一步,複製就不成立。
當物件裡含有其他物件的引用時,問題就浮現了:
class Professor
{
String name;
int age;
Professor(String name, int age) { this.name = name; this.age = age; }
}
class Student implements Cloneable
{
String name;
int age;
Professor p; // s1 與 s2 的這個引用會是一樣的
Student(String name, int age, Professor p)
{ this.name = name; this.age = age; this.p = p; }
public Object clone()
{
Student o = null;
try { o = (Student) super.clone(); }
catch (CloneNotSupportedException e) { System.out.println(e.toString()); }
return o;
}
}
public static void main(String[] args)
{
Professor p = new Professor("wangwu", 50);
Student s1 = new Student("zhangsan", 18, p);
Student s2 = (Student) s1.clone();
s2.p.name = "lisi";
s2.p.age = 30;
System.out.println("name=" + s1.p.name + ", age=" + s1.p.age); // 學生1的教授也變了
}
把 Professor 也實作 Cloneable,然後在 Student.clone() 裡手動複製它:
class Professor implements Cloneable
{
String name;
int age;
Professor(String name, int age) { this.name = name; this.age = age; }
public Object clone()
{
Object o = null;
try { o = super.clone(); }
catch (CloneNotSupportedException e) { System.out.println(e.toString()); }
return o;
}
}
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 o = null;
try { o = (Student) super.clone(); }
catch (CloneNotSupportedException e) { System.out.println(e.toString()); }
o.p = (Professor) p.clone(); // 關鍵:重新指定為新的複本
return o;
}
}
public static void main(String[] args)
{
Professor p = new Professor("wangwu", 50);
Student s1 = new Student("zhangsan", 18, p);
Student s2 = (Student) s1.clone();
s2.p.name = "lisi";
s2.p.age = 30;
System.out.println("name=" + s1.p.name + ", age=" + s1.p.age); // 學生1的教授不變
}
這種做法缺點很明顯:物件樹每深一層,就得改一次 clone()。若引用層級多、結構複雜,維護成本會迅速失控。
把物件寫進串流稱為序列化(Serialization),圈內戲稱「醃鹹菜」;從串流讀回來則叫反序列化,也就是「回鮮」。重點是寫進串流的是一份複本,原物件仍留在記憶體裡,所以鹹菜還能回鮮。
public Object deepClone()
{
// 將物件寫到流裡
ByteArrayOutputStream bo = new ByteArrayOutputStream();
ObjectOutputStream oo = new ObjectOutputStream(bo);
oo.writeObject(this);
// 從流裡讀出來
ByteArrayInputStream bi = new ByteArrayInputStream(bo.toByteArray());
ObjectInputStream oi = new ObjectInputStream(bi);
return (oi.readObject());
}
完整範例:
class Professor implements Serializable
{
String name;
int age;
Professor(String name, int age) { this.name = name; this.age = age; }
}
class Student implements Serializable
{
String name;
int age;
Professor p;
Student(String name, int age, Professor p)
{ this.name = name; this.age = age; this.p = p; }
public Object deepClone() throws IOException,
OptionalDataException, ClassNotFoundException
{
ByteArrayOutputStream bo = new ByteArrayOutputStream();
ObjectOutputStream oo = new ObjectOutputStream(bo);
oo.writeObject(this);
ByteArrayInputStream bi = new ByteArrayInputStream(bo.toByteArray());
ObjectInputStream oi = new ObjectInputStream(bi);
return (oi.readObject());
}
}
public static void main(String[] args)
{
Professor p = new Professor("wangwu", 50);
Student s1 = new Student("zhangsan", 18, p);
Student s2 = (Student) s1.deepClone();
s2.p.name = "lisi";
s2.p.age = 30;
System.out.println("name=" + s1.p.name + ", age=" + s1.p.age); // 學生1的教授不變
}
使用這個方法的前提是:物件本身以及它內部所有引用到的物件都必須可序列化。若某些欄位礙於設計無法序列化,可以考慮宣告為 transient,把它們排除在複製範圍之外。
物件結構淺、層級少,用 clone 直觀且效能好;結構深或含有大量集合,序列化的實作成本反而更低,也不易漏掉某一層。兩者各有適用場景,重點是別再把 Object.clone() 當成深拷貝使用。