克隆,和容易理解,複製一個一模一樣的物件,克隆羊,克隆牛,克隆Java物件都是一個意思。
在Java中要克隆一個物件,只需實現Cloneable介面,重寫clone方法,看似簡單,但實際有坑。
讀者可以嘗試構建如下物件並進行clone
public class User implements Cloneable{private String name; private Integer id; public User(String name, Integer id) { this.name = name; this.id = id;}//省略get set。。。@Overrideprotected User clone() throws CloneNotSupportedException {return (User) super.clone();}@Overridepublic String toString() {return "User{" +"name='" + name + ''' +", id=" + id +'}';}}
public class UserClone {public static void main(String[] args) throws CloneNotSupportedException {User user1 = new User("aaa",1);System.out.println(user1.toString());User user2 = user1.clone();user2.setName("bbb");System.out.println(user2.toString()); System.out.println(user1.toString());}}
從上述結果看clone並沒有任何問題,繼續,我們嘗試構建如下物件並克隆:
public class User implements Cloneable{private String name; private Integer id; private Sex sex; public User(String name, Integer id,Sex sex) {this.name = name; this.id = id; this.sex = sex;}//省略get [email protected] User clone() throws CloneNotSupportedException {return (User) super.clone();}@Overridepublic String toString() {return "User{" +"name='" + name + ''' +", id=" + id +", sex=" + sex +'}';}}
public class Sex {private Integer sex; public Sex(Integer sex) {this.sex = sex;}@Overridepublic String toString() {return "Sex{" +"sex=" + sex +'}';}}
public class UserClone {public static void main(String[] args) throws CloneNotSupportedException {Sex sex0 = new Sex(0);User user1 = new User("aaa",1,sex0);System.out.println(user1.toString());User user2 = user1.clone();user2.getSex().setSex(1);System.out.println(user2.toString());System.out.println(user1.toString());}}
此時clone就會有問題了,修改了user2的sex屬性後,user1的sex也被一起修改。
講到這裏引入本文最重要的兩個概念:淺克隆和深克隆,分別對應前後兩個例子
Java中存在基本型別和引用型別,本文中第二例clone失敗的物件中,就存在引用型別,當我們在clone包含引用型別的物件時需要將引用型別物件(對應本例中的Sex)也實現Cloneable介面,同時在被克隆物件(User)的clone方法中呼叫引用型別物件(Sex)的clone,具體如下:
@Overrideprotected User clone() throws CloneNotSupportedException {User user = (User) super.clone();user.sex = user.sex.clone(); return user;}
這種clone就是深克隆