Java的clone方法可以用于對象的復制,但是它有深拷貝和淺拷貝之分。
淺拷貝是指將原對象的引用地址復制給新對象,新對象所引用的依然是原對象的屬性和方法。示例代碼如下:
public class Person implements Cloneable { private String name; private int age; private Listhobbies; public Person(String name, int age, List hobbies) { this.name = name; this.age = age; this.hobbies = hobbies; } public List getHobbies() { return hobbies; } public void setHobbies(List hobbies) { this.hobbies = hobbies; } public Person clone() throws CloneNotSupportedException { return (Person) super.clone(); } } public class Main { public static void main(String[] args) throws CloneNotSupportedException { Person p1 = new Person("Tom", 20, Arrays.asList("reading", "running", "swimming")); Person p2 = p1.clone(); System.out.println("p1:" + p1 + ", p2:" + p2); System.out.println(p1.getHobbies() == p2.getHobbies()); } }
輸出結果如下:
p1: Person@15db9742, p2: Person@6d06d69c true
可以看出p1和p2的引用地址不同,但是它們的hobbies屬性引用地址相同。
深拷貝則是在拷貝對象時將其所有屬性都進行拷貝,即新對象和原對象互不影響。示例代碼如下:
public class Person implements Cloneable { private String name; private int age; private Listhobbies; public Person(String name, int age, List hobbies) { this.name = name; this.age = age; this.hobbies = hobbies; } public List getHobbies() { return hobbies; } public void setHobbies(List hobbies) { this.hobbies = hobbies; } public Person clone() throws CloneNotSupportedException { Person clone = (Person) super.clone(); clone.hobbies = new ArrayList<>(hobbies); return clone; } } public class Main { public static void main(String[] args) throws CloneNotSupportedException { Person p1 = new Person("Tom", 20, Arrays.asList("reading", "running", "swimming")); Person p2 = p1.clone(); System.out.println("p1:" + p1 + ", p2:" + p2); System.out.println(p1.getHobbies() == p2.getHobbies()); } }
輸出結果如下:
p1: Person@15db9742, p2: Person@6d06d69c false
可以看出p1和p2的hobbies屬性引用地址不同,即它們的引用關系已經斷開。