Why should the object not be cloned?

I read a lot of threads about the clone () method of the object and the Cloneable Interface, but I could not find a legitimate answer to my question. Shortly speaking:

I realized that Object has a clone () method that can “magically” clone your object. But you cannot use this method without implementing the Cloneable Interface, because this interface allows Object to use the clone () method. So why did they do this? Why shouldn't every object be cloned from the start?

+2
source share
3 answers

Cloning makes sense for some mutable data.

It does not make sense for

  • immutable data
  • .
  • , , , , GUI.
  • singleton
  • , .

. Cloneable , Cloneable, .

. , Cloneable .

+3

, ( ) clone, , clone . :

class MyClass
{
  private int val;
  public void setVal(int i)
  {
    this.val = i;
  }
  public int getVal()
  {
    return this.val;
  }
  public static void main(String st[]) throws Exception
  {
    ArrayList<MyClass> ar = new ArrayList<MyClass>();
    MyClass mc = new MyClass();
    mc.setVal(50);
    ar.add(mc);
    ArrayList<MyClass> copy =(ArrayList) ar.clone();//Since ArrayList is cloneable
    copy.get(0).setVal(10);
    System.out.print(ar.get(0).getVal());//it shows 10 instead of 50!!
  }
}

, , . , , , , .

+1

, .

         MyObject obj1 = new MyObject();
         obj2 = obj1;

Here, in this case, any changes you make to obj1 will be displayed in obj2 and vice versa, since obj2 contains the memory location obj1.

but if you do not want it, the change made in obj2 will be visible in obj1, or any change made in obj1 will be visible in obj2, then you will do Cloning. In this case, both objects will have different memory locations.

-2
source

Source: https://habr.com/ru/post/1547867/


All Articles