简单的区分一下深复制和浅复制,在java中只需要实现一下Cloneable接口,重写clone()就可以做到深复制.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
| package prototype;
import java.util.Calendar;
public class WorkExperience implements Cloneable { private String company; private Calendar start; private Calendar end;
@Override protected Object clone() throws CloneNotSupportedException { WorkExperience copy = new WorkExperience(company, start, end); return copy; }
@Override public String toString() { return "{" + "company='" + company + '\'' + ", start=" + start.getTimeInMillis() + ", end=" + end.getTimeInMillis() + '}'; }
public WorkExperience(String company, Calendar start, Calendar end) { this.company = company; this.start = start; this.end = end; }
public String getCompany() { return company; }
public void setCompany(String company) { this.company = company; }
public Calendar getStart() { return start; }
public void setStart(Calendar start) { this.start = start; }
public Calendar getEnd() { return end; }
public void setEnd(Calendar end) { this.end = end; } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
| package prototype;
public class Resume implements Cloneable { private String name; private int age; private WorkExperience workExperience;
@Override protected Object clone() throws CloneNotSupportedException { Resume copy = new Resume(name, age); copy.setWorkExperience((WorkExperience) this.workExperience.clone()); return copy; }
@Override public String toString() { return "Resume{" + "name='" + name + '\'' + ", age=" + age + ", workExperience=" + workExperience + '}'; }
public Resume(String name, int age) { this.name = name; this.age = age; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public int getAge() { return age; }
public void setAge(int age) { this.age = age; }
public WorkExperience getWorkExperience() { return workExperience; }
public void setWorkExperience(WorkExperience workExperience) { this.workExperience = workExperience; } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| package prototype;
import java.util.Calendar;
public class Main { public static void main(String[] args) throws CloneNotSupportedException { Resume r1 = new Resume("jack", 19); r1.setWorkExperience(new WorkExperience("google", Calendar.getInstance(), Calendar.getInstance())); System.out.println("r1: " + r1);
Resume r2 = (Resume) r1.clone(); r2.setName("lucy"); r2.getWorkExperience().setCompany("facebook"); Calendar yesterday = Calendar.getInstance(); yesterday.add(Calendar.DATE, -1); r2.getWorkExperience().setEnd(yesterday); System.out.println("r2: " + r2); } }
|