当我克隆父对象时,它会修改原始父对象的子对象

When I clone a Parent Object, it modifies the child objects of original Parent

我正在尝试克隆一个具有数组的对象,然后该数组中的每个元素也具有不同对象的数组。 对象结构如下:

学校 - SchClass[] - 学生[]

我有一个助手 class,它有下面一行代码来克隆 School 对象。

Helper.java:

schoolClone = (School) originalSchool.clone();

School.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

public object SchClass(){
    SchClass schClass = new SchClass();
    schClass.students = (Student[]) this.students.clone();
    return schClass;
}

Student.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;
}

如果我从 schoolClone 对象中删除一个学生,它也会从 originalSchool 对象中删除(这是我的问题)** 但是,如果我从 schoolClone 对象中删除了任何 schClass 对象,originalSchool 对象将保持原样并且仅在克隆对象上修改数据。

有没有办法可以从 schoolClone 对象中删除学生,但它不会影响我的原始 School 对象。

感谢任何帮助。

我认为您使用的是浅克隆而不是深克隆。你必须使用深度克隆并根据你的要求覆盖克隆方法。

  1. 当你克隆一个数组时,它只克隆数组,而不是数组中的元素,
  2. 如果您复制了一个包含 "children" 个对象的对象,并且这些 "children" 个对象有一个引用 "parent" 的字段,则必须更新该字段的值以便它引用父级的克隆。

我个人像避免瘟疫一样避免clone。我宁愿使用复制构造函数。