参考 : List对象深度拷贝_dinghuan2011的博客-CSDN博客
注 : 被复制的对象必须实现 Serializable 接口
拷贝实现如下
import java.io.*;
import java.util.LinkedList;
import java.util.List;
/**
* @Auther: liyue
* @Date: 2020/6/30 10:57
* @Description:
*/
public class ListUtil {
public static void main(String[] args) throws Exception {
List<Test> list = new LinkedList<>();
list.add(new Test("1", "2"));
List<Test> list2 = deepCopy(list);
System.err.println(list.get(0));
System.err.println(list2.get(0));
}
@SuppressWarnings("unchecked")
public static <T> List<T> deepCopy(List<T> src) {
List<T> dest = null;
try {
ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(byteOut);
out.writeObject(src);
ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray());
ObjectInputStream in = new ObjectInputStream(byteIn);
dest = (List<T>) in.readObject();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return dest;
}
}
Test.java
import java.io.Serializable;
/**
* @Auther: liyue
* @Date: 2020/6/30 10:57
* @Description:
*/
public class Test implements Serializable {
private static final long serialVersionUID = 7446300906378730156L;
private String name;
private String age;
public Test() {
}
public Test(String name, String age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
}
END。