在 Java 中,深拷贝(Deep Copy)和浅拷贝(Shallow Copy)是对象拷贝的两种方式,主要区别在于它们如何处理对象的内部引用。
目录
一、浅拷贝(Shallow Copy)
浅拷贝是指仅拷贝对象的基本类型字段和引用类型字段的引用,而不是引用类型所指向的对象本身。因此,浅拷贝后的对象与原对象的引用类型字段共享相同的对象。如果原对象或拷贝对象中的引用类型被修改,两个对象都会受到影响。
实现方式
通过 clone()
方法实现浅拷贝。需要类实现 Cloneable
接口,并重写 clone()
方法。
class Person implements Cloneable {
String name;
int age;
Address address;
public Person(String name, int age, Address address) {
this.name = name;
this.age = age;
this.address = address;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone(); // 浅拷贝
}
}
class Address {
String city;
public Address(String city) {this.city = city;}
}
public class Main {
public static void main(String[] args) throws CloneNotSupportedException {
Address address = new Address("New York");
Person person1 = new Person("John", 25, address);
Person person2 = (Person) person1.clone(); // 浅拷贝
System.out.println(person1.address.city); // 输出 "New York"
System.out.println(person2.address.city); // 输出 "New York"
person2.address.city = "Los Angeles";
System.out.println(person1.address.city); // 输出 "Los Angeles",由于是浅拷贝,两者共享相同的地址引用
}
}
在这个例子中,person1
和 person2
共享同一个 Address
对象,修改 person2<