如何深拷贝一个列表<Object>
How to deep copy a List<Object>
我有一个对象,这个对象还包括其他对象,像这样
学生:
public class Student implements Cloneable {
public int id;
public String name;
public List<Integer> score;
public Address address;
......
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
地址:
public class Address implements Serializable,Cloneable{
public String type;
public String value;
......
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
现在我有一个List\<Student> studentsList
如何深拷贝studentsList?如果Address中有其他对象,如何拷贝studentsList?
您需要实施正确的 clone()
方法,例如
public class Student implements Cloneable {
public int id;
public String name;
public List<Integer> score;
public Address address;
......
@Override
protected Object clone() throws CloneNotSupportedException {
Student std = new Student();
std.id = this.id; // Immutable
std.name = this.name; // Immutable
std.score = this.score.stream().collect(Collectors.toList()); // Integer is immutable
std.address = (Adress) this.address.clone();
return std;
}
我有一个对象,这个对象还包括其他对象,像这样
学生:
public class Student implements Cloneable {
public int id;
public String name;
public List<Integer> score;
public Address address;
......
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
地址:
public class Address implements Serializable,Cloneable{
public String type;
public String value;
......
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
现在我有一个List\<Student> studentsList
如何深拷贝studentsList?如果Address中有其他对象,如何拷贝studentsList?
您需要实施正确的 clone()
方法,例如
public class Student implements Cloneable {
public int id;
public String name;
public List<Integer> score;
public Address address;
......
@Override
protected Object clone() throws CloneNotSupportedException {
Student std = new Student();
std.id = this.id; // Immutable
std.name = this.name; // Immutable
std.score = this.score.stream().collect(Collectors.toList()); // Integer is immutable
std.address = (Adress) this.address.clone();
return std;
}