初學演算法-----分而治之-為何分治有更快的速度
阿新 • • 發佈:2021-12-20
任意一個類通過克隆的方法去得出另一類,原始類叫做原型
1、任意建立一個類,讓這個類去實現一個介面Cloneable,重寫一個方法clone(),此時沒有修改clone裡面,也就是淺拷貝,不會克隆屬性
/** * 實現一個介面 Cloneable * 重寫一個方法 clone() */ public class Video implements Cloneable{ //設定兩個屬性 private String name; private Date createTime; //實現裡面的克隆方法 @Override protected Object clone() throws CloneNotSupportedException { return super.clone(); } public Video(){ } public Video(String name, Date createTime) { this.name = name; this.createTime = createTime; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } @Override public String toString() { return "Video{" + "name='" + name + '\'' + ", createTime=" + createTime + '}'; } }
2、深拷貝,修改clone裡面的方法內容,進行屬性的拷貝
/** * 實現一個介面 Cloneable * 重寫一個方法 clone() */ public class Video implements Cloneable{ //設定兩個屬性 private String name; private Date createTime; //實現裡面的克隆方法 @Override protected Object clone() throws CloneNotSupportedException { Object obj = super.clone(); Video video = (Video)obj; //將這個物件的屬性也克隆 this.createTime.clone(); return obj; } public Video(){ } public Video(String name, Date createTime) { this.name = name; this.createTime = createTime; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } @Override public String toString() { return "Video{" + "name='" + name + '\'' + ", createTime=" + createTime + '}'; } }