一、浅拷贝与深拷贝
1. 浅拷贝
- 新对象只是拷贝了原对象的地址值,原对象的任何属性发生变化,新对象的值的属性就会变化
package com.erick.copy;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
public class Demo01 {
public static void main(String[] args) {
User firstUser = new User("erick", "shanxi");
User secondUser = firstUser;
System.out.println(firstUser);
System.out.println(secondUser);
firstUser.setAddress("haha");
System.out.println(secondUser.getAddress());
}
}
@Getter
@Setter
@AllArgsConstructor
class User {
private String name;
private String address;
}
2. 深拷贝
- 新对象拷贝了原对象的所有的值,即使原对象的属性发生变化,新对象值的属性也不会变化
- 包含以下几种拷贝方式
2.1 构造器
- 用构造器来new多个不同的对象,保证属性一致即可
- 对象数量少的时候可以采取这种方式
- 对象数量多的时候,开销很大
2.2 clone方法
- 只能clone基本数据类型和String,不能clone引用类型的成员变量
- 引用类型的成员变量,克隆的时候还是浅克隆
package com.erick.copy;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
public class Demo02 {
public static void main(String[] args) {
try {
Student first = new Student("erick", "shanxi");
Student second = first.clone();
System.out.println(first==second);
System.out.println(second.getName());
first.setAddress("BEIJING");
System.out.println(second.getAddress());
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
}
}
@Getter
@Setter
@AllArgsConstructor
class Student implements Cloneable {
private String name;
private String address;
@Override
public Student clone() throws CloneNotSupportedException {
Student student = (Student) super.clone();
return student;
}
}