- java代码
- 代码说明
首先在pom.xml文件中,添加以下依赖项
org.apache.commons commons-lang3 3.8.1
其次定义一个Student类
import java.io.Serializable;
public class Students implements Serializable {
public int score;
public int Age;
}
最后通过以下的一个小函数来展现深拷贝和浅拷贝的区别
import org.apache.commons.lang3.SerializationUtils;
import java.util.ArrayList;
import java.util.List;
public class DeepCopy {
public static void main(String[] args) {
Students David = new Students();
David.Age = 15;
David.score = 90;
Students Lily = new Students();
Lily.Age = 13;
Lily.score = 95;
// 浅拷贝
List students = new ArrayList<>();
students.add(David);
students.add(Lily);
// 深拷贝
List deepCopyStudents = new ArrayList<>();
deepCopyStudents.add(SerializationUtils.clone(David));
deepCopyStudents.add(SerializationUtils.clone(Lily));
System.out.println("浅拷贝原score:" + students.get(1).score);
System.out.println("深拷贝原score:" + deepCopyStudents.get(1).score);
// 修改Lily的成绩
Lily.score = 100;
System.out.println("浅拷贝新score:" + students.get(1).score);
System.out.println("深拷贝新score:" + deepCopyStudents.get(1).score);
}
}
以上实例会打印以下内容
浅拷贝原数据:95 深拷贝原数据:95 浅拷贝新数据:100 深拷贝新数据:95代码说明
看了无数篇关于深拷贝和浅拷贝的说明文章,只能说头大。我只想实现这个功能,一堆人给我讲原理,最后还没有简单易操作的操作方式。简单理解,深拷贝后的参数不会随着实例对象的改变而改变,而浅拷贝却会有同步的改变。上例中,Lily的分数(score)调整为100后,students中的对应值也随之改变;但是deepCopyStudents 中的Lily的分数却并未改变。
浅拷贝的实现方式非常简单,常见add类命令,均为浅拷贝命令。此处不再赘述。
深拷贝的实现方式需要上述三步操作:(1)添加依赖项lang3;(2)相应的类实现序列化:implements Serializable;(3)分别拷贝:SerializationUtils.clone()。



