英文:
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?
英文:
I have an object and this object also includes other objects, like this
Student :
    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();
    }
}
Address :
public class Address implements Serializable,Cloneable{
    public String type;
    public String value;
	......
    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}
Now i have a List\<Student> studentsList  How can I deep copy studentsList?How can I copy studentsList if there are other objects in Address?
答案1
得分: 4
你需要实现一个正确的 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; // 不可变
        std.name = this.name; // 不可变
        std.score = this.score.stream().collect(Collectors.toList()); // Integer 是不可变的
        std.address = (Address) this.address.clone();
        return std;
    }
}
英文:
You need to implement a correct clone() method like
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;
    }
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论