生活随笔
收集整理的這篇文章主要介紹了
Java基础 深拷贝浅拷贝
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
Java基礎(chǔ) 深拷貝淺拷貝
- 非基本數(shù)據(jù)類型 需要new新空間
class Student implements Cloneable{private int id;private String name;private Vector course;public Student(){try{Thread.sleep(1000);System.out.println("Student Constructor called.");}catch (InterruptedException e){e.printStackTrace();}}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getId() {return id;}public void setId(int id) {this.id = id;}public Vector getCourse() {return course;}public void setCourse(Vector course) {this.course = course;}//淺拷貝public Student newInstance(){try{return (Student)this.clone();}catch (CloneNotSupportedException e){e.printStackTrace();}return null;}//深拷貝public Student deepClone(){try{Student cloning = (Student) super.clone();cloning.course = new Vector();return cloning;}catch (CloneNotSupportedException e){e.printStackTrace();}return null;}}public Object clone(){ //覆寫(xiě)clone(),深拷貝 try{ Student cloning = (Student) super.clone(); // 這里不能使用Student cloning = (Student) this.clone()的原因:正在覆寫(xiě)本類的clone()方法,如果再調(diào)用本類的函數(shù),即:this.clone(),就相當(dāng)于無(wú)限遞歸無(wú)限死循環(huán)了,最終會(huì)崩潰的。所以這里:super.clone()。cloning.courses = new Vector(); //關(guān)鍵點(diǎn):非基本數(shù)據(jù)類型的空間需要自己新開(kāi)辟一塊兒 return cloning; }catch(CloneNotSupportedException e){ e.printStackTrace(); } return null;
}
參考資料
謹(jǐn)慎覆蓋clone
Java中的clone() 深拷貝 淺拷貝
轉(zhuǎn)載于:https://www.cnblogs.com/ironbrady/p/6671860.html
總結(jié)
以上是生活随笔為你收集整理的Java基础 深拷贝浅拷贝的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。