[英]When I clone a Parent Object, it modifies the child objects of original Parent
I am trying to clone a Object which has Arrays and then each element in that Array also has Arrays of a different object.我正在尝试克隆具有 Arrays 的 Object ,然后该数组中的每个元素也具有 Arrays 的不同 ZAC696CFDE63191BC4BEB66 Object Structure is as below:
Object 结构如下:
School - SchClass[] - Students[]学校 - SchClass[] - 学生[]
I have a helper class which has the below line of code to clone the School object.我有一个助手 class,它具有以下代码行来克隆学校 object。
Helper.java:助手.java:
schoolClone = (School) originalSchool.clone();
School.java学校.java
public object School(){
School school = null;
try{
school = (School) super.clone();
}
catch (CloneNotSupportedException e) {
school = new School();
}
school.schClasses = (SchClass[]) this.schClasses.clone();
return school;
}
SchClass.java SchClass.java
public object SchClass(){
SchClass schClass = new SchClass();
schClass.students = (Student[]) this.students.clone();
return schClass;
}
Student.java学生.java
public object Student(){
Student student = null;
try{
student = (Student) super.clone();
}catch (CloneNotSupportedException e) {
student = new Student(this.getName(), this.getAge(), this.getGrade());
}
return student;
}
If I remove a student from the schoolClone object, it gets removed from the originalSchool object too (this is my problem)** however if I removed any schClass object from the schoolClone object, the originalSchool object remains as it is and the data is modified only on the cloned object. If I remove a student from the schoolClone object, it gets removed from the originalSchool object too (this is my problem)** however if I removed any schClass object from the schoolClone object, the originalSchool object remains as it is and the data is modified仅在克隆的 object 上。
Is there a way I can remove a student from the schoolClone object but it does not affect my originalSchool object.有没有办法可以从学校删除学生克隆 object 但它不会影响我原来的学校 object。
Any help is appreciated.任何帮助表示赞赏。
I personally avoid clone
like the plague.我个人避免像瘟疫一样
clone
。 I rather use copy constructors.我宁愿使用复制构造函数。
I think you are using shallow cloning instead of deep cloning.我认为您使用的是浅克隆而不是深度克隆。 you have to use deep cloning and override the clone method according to your requirements.
您必须根据您的要求使用深度克隆并覆盖克隆方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.