When overriding the clone () function, if the class has a reference field, then deep cloning is required.
@ Override
public Employee clone () throws CloneNotSupportedException {
Employee e = (Employee) super.clone ();
e.hireDay = (Date) hireDay.clone ();
return e;
}
In case this is a link to a list:
class Class {
List & lt; Class2 & gt; list;
}
Overriding done:
Class e = (Class) super.clone ();
for (int i = 0; i & lt; e.list.size (); i ++) {
e.list.get (i) .clone ();
}
return e;
Is this correct?
Answer 1, authority 100%
The clone
operation will create a new object with the same references to the same objects. If you want copies of objects in the list, you need to explicitly implement this. Those. write the following:
class B implements Cloneable {
@Override
protected Object clone () throws CloneNotSupportedException {
return super.clone ();
}
}
class A implements Cloneable {
private List & lt; B & gt; list = new ArrayList & lt; & gt; ();
@Override
protected Object clone () throws CloneNotSupportedException {
A clone = (A) super.clone ();
clone.list = new ArrayList & lt; & gt; (list.size ());
for (B b: list)
clone.list.add ((B) b.clone ());
return clone;
}
}
Answer 2, authority 71%
List does not implement Cloneable
, respectively, call clone
through a variable / field of type List & lt; T & gt;
will fail.
There are List
implementations that override clone
, such as ArrayList and LinkedList, but they do not deep copy the list. Those. they create a new list that contains the same elements.
From the documentation ArrayList.clone
Returns a shallow copy of this ArrayList instance. (The elements themselves are not copied.)
To deep copy a list, go through all the elements and clone each one.
For example, like this:
e.list = new ArrayList & lt; Class2 & gt; (list.size ());
for (Class2 item: list) e.list.add (item.clone ());
Similar question in English: How to clone ArrayList and also clone its contents?