【Java】 Java中的浅拷贝和深拷贝
先抛出结论:
浅拷贝是引用拷贝,A对象拷贝B以后,A对象和B对象指向同一块内存地址,改变A对象的属性值会触发B对象属性的改变,有安全风险
深拷贝是对象拷贝,A对象拷贝B以后,A对象和B对象指向不同的额内存地址,改变A对象的属性值不会触发B对象属性的改变,无安全风险,但是成本较高
如何实现深拷贝:
实现Clonable接口,重写clone方法
代码如下
package com.gabriel.stage.vo; import lombok.AllArgsConstructor; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; /** * @author: Gabriel * @date: 2020/3/12 0:00 * @description 测试类 */ public class TestTransfer { public static void main(String[] args) throws CloneNotSupportedException { //浅拷贝 拷贝引用 Student A1 = new Student(1,"张三"); Student B1 = A1; B1.age=2; System.out.println(A1); System.out.println(B1); System.err.println("============华丽的分割线============="); //深拷贝 拷贝内存地址 Student A2 = new Student(1, "张三"); Student B2 = (Student) A2.clone(); B2.age = 2; System.out.println(A2); System.out.println(B2); } } @Data @AllArgsConstructor @NoArgsConstructor @EqualsAndHashCode class Student implements Cloneable{ int age; String name; /** * 深拷贝实现Cloneable接口 * @return * @throws CloneNotSupportedException */ @Override public Object clone() throws CloneNotSupportedException { Student stu = null; try{ stu = (Student)super.clone(); }catch(CloneNotSupportedException e) { e.printStackTrace(); } return stu; } }