Java中的克隆是指創建一個新的對象,該對象具有與原始對象相同的屬性值。在Java中,克隆通常分為淺克隆和深克隆兩種不同的方式。
淺克隆
public class Person implements Cloneable {
private String name;
private int age;
private ArrayListhobbies;
public Person(String name, int age, ArrayListhobbies) {
this.name = name;
this.age = age;
this.hobbies = hobbies;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
// 淺克隆示例
Person person1 = new Person("John", 25, new ArrayList());
Person person2 = (Person) person1.clone();
person2.getHobbies().add("Coding");
System.out.println(person1.getHobbies()); // [Coding]
System.out.println(person2.getHobbies()); // [Coding]
如上所示,淺克隆只是復制了原始對象的所有屬性值,包括引用類型。當原始對象的引用類型修改時,克隆對象也會發生相應的修改。
深克隆
public class Person implements Cloneable {
private String name;
private int age;
private ArrayListhobbies;
public Person(String name, int age, ArrayListhobbies) {
this.name = name;
this.age = age;
this.hobbies = hobbies;
}
@Override
protected Object clone() throws CloneNotSupportedException {
Person person = (Person) super.clone();
person.setHobbies((ArrayList) person.getHobbies().clone());
return person;
}
}
// 深克隆示例
Person person1 = new Person("John", 25, new ArrayList());
Person person2 = (Person) person1.clone();
person2.getHobbies().add("Coding");
System.out.println(person1.getHobbies()); // []
System.out.println(person2.getHobbies()); // [Coding]
如上所示,深克隆通過對引用類型也進行克隆來避免原始對象和克隆對象之間的干擾。深克隆將引用類型進行了復制,因此當原始對象的引用類型修改時,不會影響克隆對象。