自定义方法实现clone方法(深拷贝)
程序员文章站
2022-04-04 08:31:32
...
首先说一下深拷贝与浅拷贝的区别
- 浅拷贝可以拷贝基本数据类型(int、String、char、Boolean等),引用类型不能拷贝(只是拷贝了地址),因为引用类型的数据栈中存放地址,堆中存放相应的属性。
- 深拷贝可以同时拷贝基本数据类型和引用数据类型
可参考浅拷贝实现(注意重写clone方法和实现Cloneable接口):https://blog.csdn.net/weixin_43960044/article/details/116444705
以Student类举例实现深拷贝,引用数据类型为Car(在student类中实现Car的拷贝)
Student类(实现Cloneable类重写clone方法):
public class Student implements Cloneable{
private String name;
private int age;
private Car car;
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;
}
public Car getCar() {
return car;
}
public void setCar(Car car) {
this.car = car;
}
public Student(String name, int age, Car car) {
this.name = name;
this.age = age;
this.car = car;
}
public Student() {
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
", car=" + car +
'}';
}
@Override
public Student clone() throws CloneNotSupportedException {
// 实现拷贝--再拷贝一个Car赋值给Sudent
Student cloneStudent = (Student) super.clone();
Car cloneCar = (Car) this.car.clone();
cloneStudent.setCar(cloneCar);
return cloneStudent;
}
}
Car类(实现Cloneable类重写clone方法):
import java.util.concurrent.Callable;
public class Car implements Cloneable {
private String brand;
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public Car() {
}
public Car(String brand) {
this.brand = brand;
}
@Override
public String toString() {
return "Car{" +
"brand='" + brand + '\'' +
'}';
}
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
测试类:
public class deepCloneTest {
public static void main(String[] args) throws CloneNotSupportedException {
Student student = new Student("柳岩", 18, new Car("奥迪"));
System.out.println(student);
// 深拷贝测试
Student student1 = student.clone();
// 修改克隆的引用对象的属性
student1.getCar().setBrand("宝马");
System.out.println(student); // Student{name='柳岩', age=18, car=Car{brand='奥迪'}}
System.out.println(student1); // Student{name='柳岩', age=18, car=Car{brand='宝马'}}
}
}
上一篇: 四十.python中的闭包
下一篇: 数据结构与算法-递归(回溯法)