在Java中,對象的拷貝可以分為淺拷貝和深拷貝。淺拷貝只是復制了對象的引用,而深拷貝則會復制對象的內容。
下面通過示例來介紹淺拷貝和深拷貝的使用場景。
淺拷貝使用場景
public class Student implements Cloneable { private String name; private int age; private Listcourses; public void setName(String name) { this.name = name; } public void setAge(int age) { this.age = age; } public void setCourses(List courses) { this.courses = courses; } public String getName() { return name; } public int getAge() { return age; } public List getCourses() { return courses; } public Object clone() throws CloneNotSupportedException { return super.clone(); } } public class Test { public static void main(String[] args) throws Exception { List courses = new ArrayList (); courses.add("math"); courses.add("english"); Student s1 = new Student(); s1.setName("Tom"); s1.setAge(18); s1.setCourses(courses); Student s2 = (Student) s1.clone(); System.out.println("s1.getCourses() == s2.getCourses():" + (s1.getCourses() == s2.getCourses())); } }
上述代碼中,我們使用了List作為Student對象的成員變量。我們知道,List是一個引用類型,淺拷貝只是拷貝了List的引用,因此s1和s2的courses指向的是同一個List對象。
因此,淺拷貝適用于成員變量都是基本類型或不可變類型的情況。
深拷貝使用場景
public class Student implements Cloneable { private String name; private int age; private Listcourses; public void setName(String name) { this.name = name; } public void setAge(int age) { this.age = age; } public void setCourses(List courses) { this.courses = courses; } public String getName() { return name; } public int getAge() { return age; } public List getCourses() { return courses; } public Object clone() throws CloneNotSupportedException { Student s = (Student) super.clone(); s.setCourses(new ArrayList ()); //深拷貝 s.getCourses().addAll(this.getCourses()); return s; } } public class Test { public static void main(String[] args) throws Exception { List courses = new ArrayList (); courses.add("math"); courses.add("english"); Student s1 = new Student(); s1.setName("Tom"); s1.setAge(18); s1.setCourses(courses); Student s2 = (Student) s1.clone(); System.out.println("s1.getCourses() == s2.getCourses():" + (s1.getCourses() == s2.getCourses())); } }
上述代碼中,在實現Student對象的clone方法時,我們使用了深拷貝來復制courses成員變量。
深拷貝適用于成員變量是引用類型,并且需要獨立出一個新的對象時。