Home java Deep clone field of type List & lt; Class & gt; in...

Deep clone field of type List & lt; Class & gt; in Java




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 {
  protected Object clone () throws CloneNotSupportedException {
   return super.clone ();
class A implements Cloneable {
  private List & lt; B & gt; list = new ArrayList & lt; & gt; ();
  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?

Previous articleemmet and phpstorm
Next articleCompare dates.

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions