假设有一个包含 5 个 Employee 对象的 EmployeeList。
我想执行该 EmployeeList 的克隆以创建一个新的 EmployeeList,我想知道我应该怎么做?
所以以下是我的班级员工:
public class Employee {
private String name;
private String ssn;
private double salary;
private String name() {
return name;
}
private void name(String name) {
this.name = name;
}
private String ssn() {
return ssn;
}
private void ssn(String ssn) {
this.ssn = ssn;
}
private double salary() {
return salary;
}
private void salary(double salary) {
this.salary = salary;
}
void initialize(String initName, String initSsn, double initSalary) {
this.name(initName);
this.ssn(initSsn);
this.salary(initSalary);
}
public Employee(String name, String ssn, double salary) {
this.initialize(name, ssn, salary);
}
public Employee clone() {
return new Employee(this.name, this.ssn, this.salary);
}
}
以下是我的班级EmployeeList:
public class EmployeeList implements Cloneable {
private Employee[] list;
private int MAX = 5;
public EmployeeList() {
list = new Employee[MAX];
for (int i = 0; i < MAX; i++)
list[i] = null;
}
public void add(Employee employee) {
list[count] = employee;
}
public Object clone() {
try {
return super.clone();
} catch (CloneNotSupportedException c) {
System.out.println(c);
return null;
}
}
}
我缩短了代码,以便更容易看到。
我的问题是:
当我执行复制时,我认为它复制了带有指向原始 Employee 对象的指针的 EmployeeList。因为当我更改原始对象时,新列表中的对象也会更改
无论如何我可以解决这个问题吗?
非常感谢你。