Java中對象拷貝的兩種方式


基本類型拷貝:

克隆是針對於對象而言的,基本類型(boolean,char,byte,short,float,double.long)已久具備自身克隆的特性.

 

    int x=1;
        int y=x;
        System.out.println(x);//1
        System.out.println(y);//1
        y=2;
        System.out.println(x);//1
        System.out.println(y);//2

 

JVM實現拷貝的目的:

大家先思考一個問題,為什么需要克隆對象?直接 new 一個對象不行嗎?

  答案是:克隆的對象可能包含一些已經修改過的屬性,而 new 出來的對象的屬性都還是初始化時候的值,所以當需要一個新的對象來保存當前對象的 “狀態” 就靠 clone 方法了。那么我把這個對象的臨時屬性一個一個的賦值給我新 new 的對象不也行嘛?

    可以是可以,但是一來麻煩不說,二來,大家通過上面的源碼都發現了 clone 是一個 native 方法,就是快啊,在底層實現的

引用的拷貝

1 //引用拷貝
2     private static void copyReferenceObject(){
3         Person p = new Person(23, "zhang");
4         Person p1 = p;
5         System.out.println(p);
6         System.out.println(p1);
7     }

 

這里打印的結果: 
Person@3654919e 
Person@3654919e 
可以看到,打印的結果是一樣的,也就是說,二者的引用是同一個對象,並沒有創建出一個新的對象。因此要區分引用拷貝和對象拷貝的區別,下面要介紹的就是對象拷貝。 

淺拷貝

  • 如果pojo中存在的是基本數據類型 ,String 除外 ,實現Cloneable 覆寫Clone 方法 這個就是淺拷貝

- code 

 1 package core.java.deeporshoawcopy;
 2 
 3 /**
 4  * @author DGW-PC
 5  * @date 2018年6月7日
 6  * @see 驗證   淺拷貝  一般要求實體類使用包裝類型 對於深拷貝 類中存在對其他類的引用,也需要實現cloneable接口
 7  */
 8 
 9 class Person implements Cloneable{
10     private String name;
11     private Integer age;
12     public String getName() {
13         return name;
14     }
15     public void setName(String name) {
16         this.name = name;
17     }
18     public Integer getAge() {
19         return age;
20     }
21     public void setAge(Integer age) {
22         this.age = age;
23     }
24     @Override
25     protected Object clone() throws CloneNotSupportedException  {
26         /*Person p=null;
27         try{
28             p=(Person) super.clone();
29         }catch (CloneNotSupportedException e) {
30         }*/
31         return super.clone();
32     }
33 }
34 
35 public class Base {
36     
37      public static void main(String[] args) throws CloneNotSupportedException {
38         Person person = new Person();
39         person.setName("a");
40         person.setAge(12);
41         Person per1=(Person) person.clone();
42         per1.setName("b");
43         per1.setAge(14);;
44         System.out.println(person.getName()+" "+person.getAge().hashCode(0));
45         System.out.println(per1.getName()+" "+per1.getAge());
46     }
47 
48 }

 內存圖:

 

 

 

深拷貝

- 如果你的POJO 存在的不是基本上數據類型,可以是自己定義類型,也可以其他包提供的類型 這里以java 提供的Data 的為例子 可以看下面的代碼 自身實現clone 方法 你在涉及到使用拷貝的時候一定要注意別的包提供的類是否出現了問題

 1  /**
 2      * Return a copy of this object.
 3      */
 4     public Object clone() {
 5         Date d = null;
 6         try {
 7             d = (Date)super.clone();
 8             if (cdate != null) {
 9                 d.cdate = (BaseCalendar.Date) cdate.clone();
10             }
11         } catch (CloneNotSupportedException e) {} // Won't happen
12         return d;
13     }

- 下面介紹一下基本深拷貝的代碼 很短 : 你一定主要 主類包裝了多少其他的引用類型的其他類,那么其他必須都要實現Cloneable 接口 以及clone (保護方法) 方法

方法原型:

仔細一看,它還是一個 native 方法,大家都知道 native 方法是非 Java 語言實現的代碼,供 Java 程序調用的,

因為 Java 程序是運行在 JVM 虛擬機上面的,要想訪問到比較底層的與操作系統相關的就沒辦法了,只能由靠近操作系統的語言來實現

 

1/*
2Creates and returns a copy of this object. The precise meaning of "copy" may depend on the class of the object.
3The general intent is that, for any object x, the expression:
41) x.clone() != x will be true
52) x.clone().getClass() == x.getClass() will be true, but these are not absolute requirements.
63) x.clone().equals(x) will be true, this is not an absolute requirement.
7*/
8protected native Object clone() throws CloneNotSupportedException;

 

 

 

需要滿足的條件:

  對於任何對象x,表達式:

  • 1)x.clone()!= x將為真
  • 2)x.clone()。getClass()== x.getClass()為true,但這不是絕對要求。
  • 3)x.clone()。equals(x)將為true,這不是絕對要求。

 

具體代碼:

 1 package core.java.deeporshoawcopy;
 2 
 3 
 4 /**
 5  * @author DGW-PC
 6  * @date 2018年6月7日
 7  * @see 實現序列化  深拷貝
 8  */
 9 
10 class Dog implements Cloneable{
11     private String name;
12 
13     public String getName() {
14         return name;
15     }
16 
17     public void setName(String name) {
18         this.name = name;
19     }
20     @Override
21     protected Object clone() throws CloneNotSupportedException {
22         return super.clone();
23     }
24 }
25 class User implements Cloneable{
26     private String name;
27     private Dog dog;
28     public String getName() {
29         return name;
30     }
31     public void setName(String name) {
32         this.name = name;
33     }
34     public Dog getDog() {
35         return dog;
36     }
37     public void setDog(Dog dog) {
38         this.dog = dog;
39     }
40     @Override
41     protected Object clone() throws CloneNotSupportedException {
42         User u=(User) super.clone(); 43         u.dog=(Dog) dog.clone(); //多個需要在全部把關系搞清楚
44         return u;
45     }
46 }
47 
48 public class ObjCloner {
49         public static void main(String[] args) throws CloneNotSupportedException {
50             Dog dog = new Dog();
51             dog.setName("田園犬");
52             User user = new User();
53             user.setDog(dog);
54             user.setName("王二");
55             User user1=(User) user.clone();
56             user1.setName("張三");
57             Dog dog2 = new Dog();
58             dog2.setName("德國牧羊犬");
59             user1.setDog(dog2);
60             System.out.println(user.getName()+"養了"+ user.getDog().getName());
61             System.out.println(user1.getName()+"養了"+ user1.getDog().getName());
62         }
63 }

 

結果:

 

類組合形式下深拷貝

  1 class Car implements Cloneable{
  2     String name;
  3 
  4     public Car(String name) {
  5         this.name = name;
  6     }
  7     @Override
  8     protected Object clone()  {
  9         Car car=null;
 10         try {
 11             car=(Car) super.clone();
 12         } catch (CloneNotSupportedException e) {
 13             e.printStackTrace();
 14         }
 15         return car;
 16     }
 17     @Override
 18     public String toString() {
 19         return "Car [name=" + name + "]";
 20     }
 21 }
 22 class Home implements Cloneable{
 23     String name;
 24     public Home(String name) {
 25         this.name = name;
 26     }
 27     @Override
 28     protected Object clone()  {
 29         Home home=null;
 30         try {
 31             home=(Home) super.clone();
 32         } catch (CloneNotSupportedException e) {
 33             e.printStackTrace();
 34         }
 35         return home;
 36     }
 37     @Override
 38     public String toString() {
 39         return "Home [name=" + name + "]";
 40     }
 41 }
 42 class Wife implements Cloneable{
 43     String name;
 44     public Wife(String name) {
 45         this.name = name;
 46     }
 47     @Override
 48     protected Object clone()  {
 49         Wife wife=null;
 50         try {
 51             wife=(Wife) super.clone();
 52         } catch (CloneNotSupportedException e) {
 53             e.printStackTrace();
 54         }
 55         return wife;
 56     }
 57     @Override
 58     public String toString() {
 59         return "Wife [name=" + name + "]";
 60     }
 61 }
 62 class Person implements Cloneable{
 63     String name;
 64     Car car;
 65     Home home;
 66     Wife wife;
 67     public Person(String name, Car car, Home home, Wife wife) {
 68         super();
 69         this.name = name;
 70         this.car = car;
 71         this.home = home;
 72         this.wife = wife;
 73     }
 74     @Override
 75     public String toString() {
 76         return "Person [name=" + name + ", car=" + car + ", home=" + home + ", wife=" + wife + "]";
 77     }
 78     @Override
 79     protected Object clone()  {
 80         Person person=null;
 81         try {
 82             person=(Person) super.clone();
 83         } catch (CloneNotSupportedException e) {
 84             e.printStackTrace();
 85         }
 86         person.car=(Car) this.car.clone();
 87         person.home=(Home) this.home.clone();
 88         person.wife=(Wife) this.wife.clone();
 89         return person;
 90     }
 91     
 92 }
 93 
 94 public class Test2 {
 95     public static void main(String[] args) {
 96         Person person = new Person("Tom", new Car("bmw"), new Home("一環以內"), new Wife("intkk"));
 97         //Person person1=person;
 98         Person person1 = (Person) person.clone();
 99         System.out.println(person);
100         System.out.println(person1);
101         person1.name="Jerry";
102         person1.home= new Home("帝國");
103         person1.car=new Car("五菱骨灰盒");
104         System.out.println(person);
105         System.out.println(person1);
106     }
107 }
View Code

問題: 當存在多個類的時候,每個類都要實現Clonebale接口,實現過於復雜: 特別是下面這段代碼: (當多個類的時候建議使用串行化方式進行clone)

    protected Object clone()  {
        Person person=null;
        try {
            person=(Person) super.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        person.car=(Car) this.car.clone();
        person.home=(Home) this.home.clone();
        person.wife=(Wife) this.wife.clone();
        return person;
    }

 

 串行化方式實現深拷貝

  實現方法:

  •   實現Serializable接口,如果類中存在組合形式的使用,那么每個類都要實現Serializable接口

 

 - 以下代碼着重注意一下 CloneObj方法 ,就行。

  1 package core.java.deeporshoawcopy;
  2 
  3 import java.io.ByteArrayInputStream;
  4 import java.io.ByteArrayOutputStream;
  5 import java.io.ObjectInputStream;
  6 import java.io.ObjectOutputStream;
  7 import java.io.Serializable;
  8 
  9 /**
 10  * @author DGW-PC
 11  * @date 2018年6月7日
 12  * @since 串行化 實現 深拷貝
 13  */
 14 
 15 class Body implements Serializable{
 16     /**
 17      * 
 18      */
 19     private static final long serialVersionUID = 1L;
 20     private String name;
 21     private Fonter fonter;
 22     private Head head;
 23     public String getName() {
 24         return name;
 25     }
 26     public void setName(String name) {
 27         this.name = name;
 28     }
 29     public Fonter getFonter() {
 30         return fonter;
 31     }
 32     public void setFonter(Fonter fonter) {
 33         this.fonter = fonter;
 34     }
 35     public Head getHead() {
 36         return head;
 37     }
 38     public void setHead(Head head) {
 39         this.head = head;
 40     }
 41     @Override
 42     public String toString() {
 43         return "Body [name=" + name + ", fonter=" + fonter + ", head=" + head + "]";
 44     }
 45     public Body(String name, Fonter fonter, Head head) {
 46         super();
 47         this.name = name;
 48         this.fonter = fonter;
 49         this.head = head;
 50     }
 51     
 52     
 53 }
 54 class Head implements Serializable{
 55     /**
 56      * 
 57      */
 58     private static final long serialVersionUID = 1L;
 59     private Integer size;
 60 }
 61 class Fonter implements Serializable{
 62     /**
 63      * 
 64      */
 65     private static final long serialVersionUID = 1L;
 66     private Integer size;
 67 }
 68 class Face implements Serializable{
 69     /**
 70      * 
 71      */
 72     private static final long serialVersionUID = 1L;
 73     private Integer size;
 74 }
 75 public class ObjClonerSeiz {
 76         
 77         private static <T>T  CloneObj(T obj){
 78             T retobj=null;
 79             try {
 80             //寫入流中
 81             ByteArrayOutputStream baos = new ByteArrayOutputStream();
 82             ObjectOutputStream oos = new ObjectOutputStream(baos);
 83             oos.writeObject(obj);
 84             //從流中讀取
 85             ObjectInputStream ios = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray()));
 86             retobj=(T) ios.readObject();
 87             }catch (Exception e) {
 88                 e.printStackTrace();
 89             }
 90             return retobj;
 91         }
 92     
 93     
 94     
 95         public static void main(String[] args) {
 96                  Body body = new Body("張三", new Fonter(), new Head());
 97                  Body body2=CloneObj(body);
 98                  System.out.println("body==body2  ====>"+(body==body2));
 99                  System.out.println("body.font==body2.font  ====>"+(body.getFonter()==body2.getFonter()));
100                  System.out.println("body.head==body2.head  ====>"+(body.getHead()==body2.getHead()));
101         }
102 }

 

總結:

  • 在Java語言中,如果需要實現深克隆,可以通過覆蓋Object類的clone()方法實現,也可以通過序列化(Serialization)等方式來實現。
  • 如果引用類型里面還包含很多引用類型,或者內層引用類型的類里面又包含引用類型,使用clone方法就會很麻煩。這時我們可以用序列化的方式來實現對象的深克隆。)
  • 實現對象克隆有兩種方式:

      1). 實現Cloneable接口並重寫Object類中的clone()方法;

      2). 實現Serializable接口,通過對象的序列化和反序列化實現克隆,可以實現真正的深度克隆

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM