【问题标题】:How to deep copy a List<Object> [duplicate]如何深拷贝 List<Object> [重复]
【发布时间】:2021-01-07 06:45:48
【问题描述】:

我有一个对象,这个对象还包括其他对象,比如这个

学生:

    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\&lt;Student&gt; studentsList我如何深拷贝studentsList?如果Address中有其他对象,我如何复制studentList?

【问题讨论】:

标签: java spring spring-boot object clone


【解决方案1】:

您需要实现一个正确的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;
    }

【讨论】:

  • 我只需要提一下std.score = new ArrayList&lt;Integer&gt;(this.score); 更容易阅读。
  • @Mohammed Deifalah :您的提及仅归功于 Integer 是不可变的。让我们想象一个List&lt;Adress&gt;,您的方法不起作用,但我的方法是在流中添加.map(a -&gt; (Adress) a.clone)。您的方法签名是浅拷贝,不应在深拷贝上下文中使用
猜你喜欢
  • 2018-10-05
  • 2013-03-12
  • 2011-02-09
  • 2011-05-12
  • 2017-10-14
  • 1970-01-01
  • 1970-01-01
  • 2016-05-07
  • 2011-03-24
相关资源
最近更新 更多