Java 深浅拷贝
定义
- 浅拷贝只复制一个对象(包括基本类型),对象内部存在的指向其他对象的引用则不复制
- 深拷贝:对象以及对象内部的引用均复制
import java.util.ArrayList;
import java.util.List;
public class Test {
static class Person
{
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public Object clone() throws CloneNotSupportedException
{
return (Person)super.clone();
}
public Object deepClone() throws CloneNotSupportedException
{
Person person = (Person)super.clone();
person.setName(new String(this.name));
return person;
}
}
浅拷贝:
1.直接引用
public static void main(String[] args)
{
Person person = new Person("lipeng",22);
Person person1 = person;
System.out.println(person1.name); // lipeng
System.out.println(person1.age); //22
person.age = 23;
person.name = "lixiaoyu";
System.out.println(person1.name); // lixiaoyu
System.out.println(person1.age); //23
}
}
==结论==:person1引用person,当person的对象值改变时,person1的跟着改变
2.调用Object类Clone函数浅拷贝
public static void main(String[] args) throws CloneNotSupportedException {
Person person = new Person("lipeng",22);
Person person1 =(Person) person.clone();
System.out.println("person == person1 is "+ (person == person1));
System.out.println("person.name == person1.name is "+ (person.name == person1.name));
}
==print==:
person == person1 is false
person.name == person1.name is true
==结论==:
调用Object的Clone的函数返回person的一个深度拷贝,person引用已经被复制,但其内部的name引用没有被复制
深度拷贝
public static void main(String[] args) throws CloneNotSupportedException {
Person person = new Person("lipeng",22);
Person person1 =(Person) person.deepClone();
System.out.println("person == person1 is "+ (person == person1));
System.out.println("person.name == person1.name is "+ (person.name == person1.name));
}
print:
person == person1 is false
person.name == person1.name is false
==结论==:
调用Object Clone函数 复制person引用,内部引用采用new函数复制,达到深度拷贝,
现在两个Person完全独立,深度拷贝必须拷贝对象所包含的所有引用。