Java基礎 深拷貝淺拷貝
- 非基本數據類型 需要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(){ //覆寫clone(),深拷貝 try{ Student cloning = (Student) super.clone(); // 這里不能使用Student cloning = (Student) this.clone()的原因:正在覆寫本類的clone()方法,如果再調用本類的函數,即:this.clone(),就相當于無限遞歸無限死循環了,最終會崩潰的。所以這里:super.clone()。cloning.courses = new Vector(); //關鍵點:非基本數據類型的空間需要自己新開辟一塊兒 return cloning; }catch(CloneNotSupportedException e){ e.printStackTrace(); } return null;
}
參考資料
謹慎覆蓋clone
Java中的clone() 深拷貝 淺拷貝