When overriding the clone () function, if the class has a reference field, then deep cloning is necessary.

@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 the list:

  class Класс { List<Класс2> list; } 

The override is done:

  Класс e = (Класс)super.clone(); for(int i = 0; i<e.list.size(); i++){ e.list.get(i).clone(); } return e; 

Is it correct?

  • Tried to do so? What happened? - default locale
  • No, not right. What you did was simply create a new list with the same objects. You need to go through the list explicitly and call clone - Artem Konovalov on each object.

2 answers 2

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<B> list = new ArrayList<>(); @Override protected Object clone() throws CloneNotSupportedException { A clone = (A) super.clone(); clone.list = new ArrayList<>(list.size()); for (B b : list) clone.list.add((B) b.clone()); return clone; } } 

    List does not implement Cloneable respectively, to call clone via a variable / field of type List<T> does not work.

    There are List implementations that override clone , for example, ArrayList and LinkedList, but they do not perform deep copy of the list. Those. they create a new list that contains the same items.

    From the ArrayList.clone documentation

    Returns a shallow copy of this ArrayList instance. (The elements themselves are not copied.)

    For a deep copy of the list you need to go through all the elements and clone each.

    For example:

     e.list = new ArrayList<Класс2>(list.size()); for (Класс2 item : list) e.list.add(item.clone()); 

    A similar question in the English version: How to clone ArrayList and also clone its contents?