0

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?

段小言
  • 12
  • 3
  • 1
    Does this answer your question? [How to clone ArrayList and also clone its contents?](https://stackoverflow.com/questions/715650/how-to-clone-arraylist-and-also-clone-its-contents) – Milgo Sep 21 '20 at 07:19

1 Answers1

4

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;
    }
IQbrod
  • 2,060
  • 1
  • 6
  • 28
  • I just need to mention that `std.score = new ArrayList(this.score);` is easier and more readable. – Mohammed Deifallah Sep 21 '20 at 07:53
  • @Mohammed Deifallah : Your mention works only thanks to `Integer` being Immutable. Let's imagine a `List` your method doesn't work but mine will by adding `.map(a -> (Adress) a.clone)` in the stream. Your method signature is a shallow copy and shouldn't be used in a deep copy context – IQbrod Sep 21 '20 at 07:55