如何深度复制一个 List\

huangapple go评论72阅读模式
英文:

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&lt;Integer&gt; 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\&lt;Student&gt; 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&lt;Integer&gt; 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;
    }

huangapple
  • 本文由 发表于 2020年9月21日 15:16:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/63987753.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定