Java 深拷貝與淺拷貝的分析_java

來源:互聯網
上載者:User

在正式的進入主題之前,我們先來瞭解下深拷貝和前拷貝的概念:

淺拷貝:

會建立一個新對象,這個對象有著原始對象屬性值的一份精確拷貝,如果屬性是基本類型,拷貝的是基本類型的值;如果屬性是記憶體位址,拷貝的就是記憶體位址,因此如果一個對象改變了這個地址就會影響到另一個對象;

深拷貝:

不僅要複製對象的所有非引用成員變數值,還要為參考型別的成員變數建立新的執行個體,並且初始化為形式參數執行個體值;

瞭解完概念之後,我們來測試下普通的對象賦值操作屬於深拷貝還是淺拷貝:

測試代碼:

public class DepthCopy {   public static void main(String[] args) {     Copy first = new Copy("hzw", 24);     Copy second = first;     second.name = "shanxi";     System.out.println(first.name);//輸出shanxi   } } class Copy {   public String name;   public int age;   public Copy(String name,int age) {     this.name = name;     this.age = age;   } } 

可以發現,在second將name屬性值修改為shanxi之後,first的name屬性值也變成了shanxi,這點就可以看出普通的對象賦值屬於淺拷貝;

明白了對象之間賦值是淺拷貝之後,接下來我們來看看複製到底是深拷貝還是淺拷貝,測試代碼是讓上面的Copy對象實現Cloneable介面裡面的clone方法:

public class DepthCopy {   public static void main(String[] args) {     Copy first = new Copy("hzw", 24);     Copy second = null;     try {       second = (Copy) first.clone();     } catch (CloneNotSupportedException e) {       e.printStackTrace();     }     second.name = "shanxi";     System.out.println(first.name);//輸出: hzw     System.out.println(first);//輸出: com.hzw.day33.Copy@7f39ebdb     System.out.println(second);//輸出: com.hzw.day33.Copy@33abb81e   } } class Copy implements Cloneable {   public String name;   public int age;   public Copy(String name,int age) {     this.name = name;     this.age = age;   }   @Override   protected Object clone() throws CloneNotSupportedException {     return super.clone();   } } 

可以看出原先建立出的對象first和複製建立出的對象second是兩個執行個體,因此對於second中name屬性的修改並不會影響first中的name屬性;但是,我們並不能單純的認為複製就是深拷貝的,比如下面這個例子:

public class DepthCopy {   public static void main(String[] args) {     Student student = new Student(95);     Copy first = new Copy("hzw", 24,student);     Copy second = null;     try {       second = (Copy) first.clone();     } catch (CloneNotSupportedException e) {       e.printStackTrace();     }     second.name = "shanxi";     second.student.score = 60;     System.out.println(first == second);//false     System.out.println(first.student == second.student);//true     System.out.println(first.student.score);//60   } } class Copy implements Cloneable {   public String name;   public int age;   public Student student;   public Copy(String name,int age,Student student) {     this.name = name;     this.age = age;     this.student = student;   }   @Override   protected Object clone() throws CloneNotSupportedException {     return super.clone();   } } class Student  {   public int score;   public Student(int score) {     this.score = score;   } } 

看到沒有呢?我們通過複製的方式建立了second,很明顯發現first和second是兩個執行個體,因為first == second輸出為false,但是first和second裡面的student對象卻是一樣的,通過second修改了student的score值之後,first裡面student的score也發生了改變,這也就是說first和second裡面的student是相同的,這也就說明了複製是淺拷貝的,我們要想實現複製的深拷貝,必須讓Copy對象裡面的Student對象也要實現Cloneable介面裡面的clone方法,並且在Copy裡面的複製方法返回Student的一個複製即可,這樣就可以保證Student的唯一啦,修改之後的代碼如下:

public class DepthCopy {   public static void main(String[] args) {     Student student = new Student(95);     Copy first = new Copy("hzw", 24,student);     Copy second = null;     try {       second = (Copy) first.clone();     } catch (CloneNotSupportedException e) {       e.printStackTrace();     }     second.name = "shanxi";     second.student.score = 60;     System.out.println(first == second);//false     System.out.println(first.student == second.student);//false     System.out.println(first.student.score);//95     System.out.println(second.student.score);//60   } } class Copy implements Cloneable {   public String name;   public int age;   public Student student;   public Copy(String name,int age,Student student) {     this.name = name;     this.age = age;     this.student = student;   }   @Override   protected Object clone() throws CloneNotSupportedException {     Copy copy = (Copy)super.clone();     copy.student = (Student) student.clone();     return copy;   } } class Student implements Cloneable {   public int score;   public Student(int score) {     this.score = score;   }   @Override   protected Object clone() throws CloneNotSupportedException {     return super.clone();   } } 

可以看到此時first和second和first.student和second.student都不是相同的,因此我們修改second的student的score之後並沒有影響到first裡的student的score值,達到了深拷貝的目的;

但是,仔細一想問題就出來了,假如我們上面例子的Student類中也存在參考型別的屬性,比如College類,那麼我們必須讓College類實現Cloneable介面,然後在Student類裡面的clone方法裡面調用College類的clone方法,在Copy類的clone方法中調用Student類的clone方法,發現沒有了,這個過程好複雜,必須讓類中的有關參考型別全部實現Cloneable介面,感覺好麻煩是不是,好的,接下來就該牛人登場了;

解決深拷貝問題最好的方式就是採用序列化方式,這樣各種類均不用實現Cloneable介面的,直接序列化還原序列化就可以啦,我們來見識下吧。

import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable;  public class DepthCopy {   public static void main(String[] args) {     College school = new College("nongda");     Student student = new Student(95, school);     Copy copy = new Copy("hzw",23, student);     Copy another = null;//表示還原序列化出來的類執行個體     //進行序列化操作     try {       FileOutputStream fos = new FileOutputStream(new File("d:/copy.txt"));       ObjectOutputStream oos = new ObjectOutputStream(fos);       oos.writeObject(copy);     } catch (Exception e) {       e.printStackTrace();     }     //進行還原序列化操作     FileInputStream fis;     try {       fis = new FileInputStream(new File("d:/copy.txt"));       ObjectInputStream ois = new ObjectInputStream(fis);       another = (Copy) ois.readObject();     } catch (Exception e) {       e.printStackTrace();     }     System.out.println(copy == another);//false     System.out.println(copy.student == another.student);//false     System.out.println(copy.student.school == another.student.school);//false     another.student.school.schoolName = "wuda";     System.out.println(copy.student.school.schoolName);//nongda   } } class Copy implements Serializable {   public String name;   public int age;   public Student student;   public Copy(String name,int age,Student student) {     this.name = name;     this.age = age;     this.student = student;   } } class Student implements Serializable {   public int score;   public College school;   public Student(int score,College school) {     this.score = score;     this.school = school;   } } class College implements Serializable {   public String schoolName;   public College(String schoolName) {     this.schoolName = schoolName;   } } 

從輸出就可以看出來,還原序列化之後產生的對象完全就是對原對象的一份拷貝,除了屬性值相同之外並不和原對象有任何關係,因此當我們修改還原序列化產生對象的schoolName為"wuda"的時候並沒有修改原來執行個體的schoolName值,還是輸出"nongda",因此達到了真正的深拷貝效果,但是要想實現序列化,所有的有關類都必須實現Serializable介面,這總也比既實現Cloneable介面又實現clone方法更方便吧。

以上就是對Java 深拷貝和淺拷貝的詳細講解,有需要的可以參考下。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.