Dev-No.02 Cloneable与Clone(深拷贝、浅拷贝)
程序员文章站
2022-07-06 09:14:02
...
共享heap中的空间
实现clone()方法条件:
- 需拷贝的类实现Cloneable接口(该接口内没有方法)、
- 实现 public Object clone() 方法
clone()为浅拷贝,若想改为深拷贝,需类中可变域生成新的实例
//浅拷贝:
public class ShallowCopy implements Cloneable{ private Date begin; public Date getBegin(){return this.begin;} public void setBegin(Date d){this.begin=d;} public Object clone(){ Object obj=null; try { obj=super.clone(); }catch (CloneNotSupportedException ex) { ex.printStackTrace(); } return obj; } }
//深拷贝:
public class DeepCopy implements Cloneable{ private Date begin; public Date getBegin(){return this.begin;} public void setBegin(Date d){this.begin=d;} public Object clone(){ DeepCopy obj=null; try{ obj=(DeepCopy)super.clone(); }catch (CloneNotSupportedException ex) { ex.printStackTrace(); } obj.setBegin((Date)this.getBegin().clone()); return obj; } }
上一篇: Java深拷贝和浅拷贝的区别
下一篇: 钉钉电脑版怎么订阅国家法定节日日历?