What is the reason for cloning an object in java?

I read Joshua Bloch Effective Java. There he says that he does not use the interface Clonable. I am a little noob, so my question is: what is the use case when cloning is required in code? Can someone give a sticky example so that I can understand the concept?

+4
source share
4 answers

Interface A clone()provides a mechanism for creating a shallow copy of an object. That is, by default, more memory will be allocated for the copy, and each part of the original will be copied to the copy. In contrast, simply assigning an instance of an object to a variable will result in an additional reference to the same object. Although the cloned object itself is a genuine copy, the elements contained in it refer to those mentioned in the original by default. If you need a real "deep" copy, the method clone()should be specialized to create clones of its members.

One of the possible options for using the interface clone()is to implement the version history of the object, which allows you to roll back its older version. This can be used on transactional systems such as databases.

copy-on-write, , .

* newacct.

+5

,

... clone() , , , . , , , . , . , , , , . clone() .

+2

Java. :

MyObj first = new MyObj(someOwner, someTag, someInt);
MyObj second = first;

( ) . MyObj. , clone(), - , . , , : clone , - , . , :

MyObj third = (MyObj) first.clone();

clone() first / MyObj. , - , .

: - . MyObj, , Person NameTag. MyObj, , , , NameTag (, , ). - MyObj NameTag "--" "" "MyObj". , :

class MyObj implements Cloneable {

    private Person owner;
    private NameTag tag;
    private int size; 

    public MyObj(Person owner, NameTag tag, int size) {
         this.owner = owner;
         this.tag = tag;
         this.size = size;
    }

    public Object clone() {

        MyObj result;

        //call all super clone() methods before doing class specific work
        //this ensures that no matter where you are in the inheritance heirarchy,
        //a deep copy is made at each level.
        try {
            result = (MyObj) super.clone();
        }
        catch (CloneNotSupportedException e) {
            throw new RuntimeException
            ("Super class doesn't implement cloneable");
        }

        //work specific to the MyObj class
        result.owner = owner;     //We want the reference to the Person, not a clone
        result.tag = tag.clone()  //We want a deep copy of the NameTag
        result.size = size;       //ints are primitive, so this is a copy operation    

        return result;
}
+1

One example is the protective copying of parameters (Effective Java article 39: make protective copies if necessary)

class X {
  private byte[] a;

  X(byte[] a) {
      this.a = a.clone();
  }
...
+1
source

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


All Articles