How to deep clone an object list that contains several objects in java? -



How to deep clone an object list that contains several objects in java? -

say there employeelist contains 5 employee object.

i want perform clone of employeelist create new employeelist, , wondering how should that?

so next class employee:

public class employee { private string name; private string ssn; private double salary; private string name() { homecoming name; } private void name(string name) { this.name = name; } private string ssn() { homecoming ssn; } private void ssn(string ssn) { this.ssn = ssn; } private double salary() { homecoming 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() { homecoming new employee(this.name, this.ssn, this.salary); } }

and next class employeelist:

public class employeelist implements cloneable { private employee[] list; private int max = 5; public employeelist() { list = new employee[max]; (int = 0; < max; i++) list[i] = null; } public void add(employee employee) { list[count] = employee; } public object clone() { seek { homecoming super.clone(); } grab (clonenotsupportedexception c) { system.out.println(c); homecoming null; } } }

i shorten code it`s easier see.

my problem is:

when performed copy, think copied employeelist pointers points original employee objects. because when alter original objects, 1 in new list changes well

is there anyway can fixed?

thank much.

yup, did thought did - cloned array including values. array values in case pointers instances of employee, got 2nd array pointing same employees. called shallow copy. if want total re-create need like

public object clone() { seek { employeelist re-create = (employeelist) super.clone(); if (list!=null) { copy.list = new employee[list.length]; (int i=0; i<list.length; i++) { copy.list[i] = (employee)list[i].clone(); } } else { copy.list = null; } homecoming copy; } grab (clonenotsupportedexception c) { system.out.println(c); homecoming null; } }

you need create employee clonable. when youre dealing graph of objects each object's clone() method needs recursively clone info members until nail primitives (like double) or immutable classes (classes cannot changed 1 time constructed - string in case)

java clone deep-copy

Comments

Popular posts from this blog

web services - java.lang.NoClassDefFoundError: Could not initialize class net.sf.cglib.proxy.Enhancer -

Accessing MATLAB's unicode strings from C -

javascript - mongodb won't find my schema method in nested container -