深拷贝和浅拷贝的java代码示例
时间: 2023-06-01 15:05:50 浏览: 110
好的,以下是深拷贝和浅拷贝的 Java 代码示例:
// 浅拷贝示例
class Person implements Cloneable {
public String name;
public int age;
public List<String> skills;
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
Person person1 = new Person();
person1.name = "Alice";
person1.age = 20;
person1.skills = new ArrayList<>(Arrays.asList("code", "music"));
Person person2 = (Person) person1.clone();
System.out.println(person1.skills == person2.skills); // true。拷贝后的 skills 引用指向同一个 List 对象
// 深拷贝示例
class Person implements Cloneable {
public String name;
public int age;
public List<String> skills;
public Object clone() throws CloneNotSupportedException {
// 先调用 super.clone() 创建新对象
Person person = (Person) super.clone();
// 对 skills 字段进行深拷贝
person.skills = new ArrayList<>(this.skills);
return person;
}
}
Person person1 = new Person();
person1.name = "Alice";
person1.age = 20;
person1.skills = new ArrayList<>(Arrays.asList("code", "music"));
Person person2 = (Person) person1.clone();
System.out.println(person1.skills == person2.skills); // false。拷贝后的 skills 引用指向不同的 List 对象
阅读全文