如何深度复制一个 List\

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

How to deep copy a List<Object>

问题

我有一个对象,这个对象还包括其他对象,像这样

学生:

  1. public class Student implements Cloneable {
  2. public int id;
  3. public String name;
  4. public List<Integer> score;
  5. public Address address;
  6. ......
  7. @Override
  8. protected Object clone() throws CloneNotSupportedException {
  9. return super.clone();
  10. }
  11. }

地址:

  1. public class Address implements Serializable, Cloneable {
  2. public String type;
  3. public String value;
  4. ......
  5. @Override
  6. protected Object clone() throws CloneNotSupportedException {
  7. return super.clone();
  8. }
  9. }

现在我有一个 List<Student> studentsList,如何进行深层复制?如果在地址中有其他对象,我该如何复制 studentsList?

英文:

I have an object and this object also includes other objects, like this

Student :

  1. public class Student implements Cloneable {
  2. public int id;
  3. public String name;
  4. public List&lt;Integer&gt; score;
  5. public Address address;
  6. ......
  7. @Override
  8. protected Object clone() throws CloneNotSupportedException {
  9. return super.clone();
  10. }
  11. }

Address :

  1. public class Address implements Serializable,Cloneable{
  2. public String type;
  3. public String value;
  4. ......
  5. @Override
  6. protected Object clone() throws CloneNotSupportedException {
  7. return super.clone();
  8. }
  9. }

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() 方法,类似于以下的代码:

  1. public class Student implements Cloneable {
  2. public int id;
  3. public String name;
  4. public List<Integer> score;
  5. public Address address;
  6. // ......
  7. @Override
  8. protected Object clone() throws CloneNotSupportedException {
  9. Student std = new Student();
  10. std.id = this.id; // 不可变
  11. std.name = this.name; // 不可变
  12. std.score = this.score.stream().collect(Collectors.toList()); // Integer 是不可变的
  13. std.address = (Address) this.address.clone();
  14. return std;
  15. }
  16. }
英文:

You need to implement a correct clone() method like

  1. public class Student implements Cloneable {
  2. public int id;
  3. public String name;
  4. public List&lt;Integer&gt; score;
  5. public Address address;
  6. ......
  7. @Override
  8. protected Object clone() throws CloneNotSupportedException {
  9. Student std = new Student();
  10. std.id = this.id; // Immutable
  11. std.name = this.name; // Immutable
  12. std.score = this.score.stream().collect(Collectors.toList()); // Integer is immutable
  13. std.address = (Adress) this.address.clone();
  14. return std;
  15. }

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:

确定