import java.text.SimpleDateFormat; import java.util.Date; public class AboutCloneOfDate implements Cloneable { private Date date; public AboutCloneOfDate(){ this.date = new Date(); } public AboutCloneOfDate(Date newDate) { this.date = newDate; } public Object clone() {//浅拷贝 Object obj = null; try { obj = super.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } return obj; } // public Object clone() {//深拷贝 // AboutCloneOfDate obj = null; // try { // obj =(AboutCloneOfDate)super.clone(); // // } catch (CloneNotSupportedException e) { // e.printStackTrace(); // } // obj.setDate((Date)this.getDate().clone()); // return obj; // } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } /** * @param args */ public static void main(String[] args) throws Exception { // TODO Auto-generated method stub SimpleDateFormat sft = new SimpleDateFormat("yyyy-MM-dd"); Date temp = sft.parse("1989-1-11"); AboutCloneOfDate a = new AboutCloneOfDate(); a.setDate(temp); System.out.println(a.getDate()); AboutCloneOfDate cloneofa = (AboutCloneOfDate) a.clone(); temp.setMonth(4); System.out.println(a.getDate()); System.out.println(cloneofa.getDate()); } }
测试前提条件是拷贝前只能有一个Date对象,因为如果clone前a.setDate(new Date()),clone后又一个cloneofa.setDate(new Date()),那就不用clone了,a与cloneofa中的属性date已经指向不同的java.util.Date对象了。
上述代码shallow clone时输出结果是
Wed Jan 11 00:00:00 CST 1989 Thu May 11 00:00:00 CDT 1989 Thu May 11 00:00:00 CDT 1989
shallow clone说明a中的date指向的temp对象发生改变时,cloneofa中的date也发生了相同的变化,,说明clone前后都指向同一个temp对象,实现了deep clone。
deep clone时输出结果是
Wed Jan 11 00:00:00 CST 1989 Thu May 11 00:00:00 CDT 1989 Wed Jan 11 00:00:00 CST 1989
deep clone说明a中的date指向的temp对象发生改变时,cloneofa中的date并没有受到影响,实现了deep clone。