浅谈深拷贝和浅拷贝
package com.wgw.entities; public class MyDate { private int year; private int month; private int day; public int getYear() { return year; } public void setYear(int year) { this.year = year; } public int getMonth() { return month; } public void setMonth(int month) { this.month = month; } public int getDay() { return day; } public void setDay(int day) { this.day = day; } public void set(int year,int month,int day) { this.year = year; this.month = month; this.day = day; } public MyDate(MyDate d){ d.set(d.year, d.month, d.day); } public MyDate(int year,int month,int day) { this.set(year, month, day); } public String toString() { return year + "年" + String.format("%02d",month) + "月" + String.format("%02d", day) + "日"; } public boolean equals(MyDate d) { return this==d || d!=null &&this.year==d.year&&this.month==d.month&&this.day==d.day; } }
package com.wgw.entities; public class Person { private String name; private MyDate birthday; private String sex; public String getName() { return name; } public void setName(String name) { this.name = name; } public MyDate getBirthday() { return birthday; } public void setBirthday(MyDate birthday) { this.birthday = birthday; } public String isSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public Person(String name,MyDate birthday,String sex) { //这样传参的时候不会new mydate this.set(name, birthday, sex); } public Person(Person p) { //深度拷贝的时候会New this(p.name,new MyDate(p.birthday),p.sex); } // public Person(Person p) { //深度拷贝的时候会New // this(p.name,p.birthday,p.sex); // } public void set(String name,MyDate birthday,String sex) { this.name = name; this.birthday = birthday; this.sex = sex; } public String toString() { return name + "," + birthday.toString() + sex; } public boolean equals(Person p) { return this==p||p.name ==this.name&&p.birthday == this.birthday && p.sex == this.sex; } }
package com.wgw.test; import com.wgw.entities.MyDate; import com.wgw.entities.Person; public class Test { public static void main(String[] args) { MyDate d1 = new MyDate(1997,9,20); MyDate d2 = new MyDate(2017,4,5); System.out.println(d1.toString()); System.out.println(d2.toString()); //打印p1内容 Person p1 = new Person("Bob",d1,"男"); System.out.println(p1.toString()); //拷贝构造 Person p2 = new Person(p1); System.out.println(p2.toString()); //改变p2的内容,测试p1是否也跟着改变 p2.getBirthday().set(1996,10,1); p2.setName("Mary");//浅构造的时候把这里注释,equals返回true p2.setSex("女"); System.out.println(p2.toString()); System.out.println(p1.toString()); System.out.println(p2.equals(p1));//birth对象是不同的 // p1.set("Alice", d2, "女"); // System.out.println(p1.toString()); // System.out.println(p2.toString()); // // System.out.println(p2.equals(p1));//birth对象是不同的 // d1.setYear(3010); // d1.toString(); // p1.set("Jack", d1, "男"); // // Person p3 = new Person("Jack", d1, "男"); // System.out.println(p3.equals(p1)); } }
分别注释浅拷贝和深拷贝的结果: