如何在Java中深度克隆包含多个对象的对象列表? [英] How to deep clone an object list that contains several objects in java?
问题描述
说有一个包含5个Employee对象的EmployeeList。
Say there is an EmployeeList that contains 5 Employee object.
我想对该EmployeeList进行克隆以创建一个新的EmployeeList,我想知道应该怎么做?我这样做吗?
I want to perform a clone of that EmployeeList to make a new EmployeeList, and I am wondering how should I do that?
下面是我的班级雇员:
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:
And the following is my class 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;
}
}
}
我将代码缩短了更容易看到。
I shorten the code so it`s easier to see.
我的问题是:
执行复制时,我认为它复制了EmployeeList带有指向原始Employee对象的指针。因为当我更改原始对象时,新列表中的对象也会更改
无论如何,我是否可以解决该问题?
Is there anyway I can get that fixed?
非常感谢。
推荐答案
是的,它确实按照您的想法做了-它克隆了包含其值的数组。在这种情况下,数组值是指向Employee实例的指针,因此您获得了指向同一Employees的第二个数组。它称为浅拷贝。如果您想要完整副本,则需要类似
yup, it did exactly what you thought it did - it cloned your array including its values. the array values in this case are pointers to instances of Employee, so you got a 2nd array pointing to the same Employees. its called a shallow copy. if you want a full copy you need something like
public Object clone() {
try {
EmployeeList copy = (EmployeeList) super.clone();
if (list!=null) {
copy.list = new Employee[list.length];
for (int i=0; i<list.length; i++) {
copy.list[i] = (Employee)list[i].clone();
}
} else {
copy.list = null;
}
return copy;
} catch (CloneNotSupportedException c) {
System.out.println(c);
return null;
}
}
您还需要使Employee变得可克隆。
通常在您处理对象图时,每个对象的clone()方法都需要递归地克隆其数据成员,直到您击中基元(例如您的 double
)或不可变类(一旦构造便无法更改的类,例如 String
)
you will also need to make Employee clonable.
generally when youre dealing with a graph of objects each object's clone() method needs to recursively clone its data members until you hit primitives (like your double
) or immutable classes (classes that cannot be changed once constructed - like String
in your case)
这篇关于如何在Java中深度克隆包含多个对象的对象列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!