在Java中,深拷贝和浅拷贝是两种不同的对象复制方式。
-
浅拷贝:创建一个新对象,然后将原对象的非静态字段复制到新对象中。如果字段是值类型的,那么对该字段执行逐位复制。如果字段是引用类型的,则复制引用但不复制引用的对象。因此,原始对象及其副本引用同一个对象。
-
深拷贝:创建一个新对象,并将原对象的非静态字段复制到新对象中。如果字段是值类型的,那么对该字段执行逐位复制。如果字段是引用类型的,则递归地复制引用的对象,直到遇到值类型为止。因此,原始对象及其副本引用不同的对象。
以下是一个简单的Java代码示例,展示了浅拷贝和深拷贝的区别:
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;}// 浅拷贝public Object clone() throws CloneNotSupportedException {return super.clone();}// 深拷贝public Person deepClone() {return new Person(new String(this.name), this.age, new Address(this.address.city, this.address.street));}
}class Address {String city;String street;public Address(String city, String street) {this.city = city;this.street = street;}
}public class Main {public static void main(String[] args) throws CloneNotSupportedException {Address address = new Address("北京", "朝阳路");Person person1 = new Person("张三", 30, address);Person person2 = (Person) person1.clone(); // 浅拷贝Person person3 = person1.deepClone(); // 深拷贝System.out.println("person1: " + person1.address.city + ", " + person1.address.street);System.out.println("person2: " + person2.address.city + ", " + person2.address.street);System.out.println("person3: " + person3.address.city + ", " + person3.address.street);person1.address.city = "上海";System.out.println("修改person1的地址后:");System.out.println("person1: " + person1.address.city + ", " + person1.address.street);System.out.println("person2: " + person2.address.city + ", " + person2.address.street);System.out.println("person3: " + person3.address.city + ", " + person3.address.street);}
}
输出结果:
person1: 北京, 朝阳路
person2: 北京, 朝阳路
person3: 北京, 朝阳路
修改person1的地址后:
person1: 上海, 朝阳路
person2: 上海, 朝阳路
person3: 北京, 朝阳路
从输出结果可以看出,浅拷贝时,person1和person2引用的是同一个Address对象,而深拷贝时,person1和person3引用的是两个不同的Address对象。