【发布时间】:2020-03-03 16:44:46
【问题描述】:
我正在尝试克隆一个具有数组的对象,然后该数组中的每个元素也具有不同对象的数组。 对象结构如下:
学校 - SchClass[] - 学生[]
我有一个帮助类,它有下面的代码行来克隆 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 对象中删除学生,但不会影响我的 originalSchool 对象。
感谢任何帮助。
【问题讨论】: