Clarity needed on cloning: Shallow copying of objects is NOT just assigning object reference variable to another variable or is it? [duplicate]

StackOverflow https://stackoverflow.com/questions/23654502

  •  22-07-2023
  •  | 
  •  

Domanda

I asked a question about cloning in java and got answers saying deep copy creates a new instance of the object carrying the same state and data in the member variables. I was told shallow copying is just assigning an object reference to another reference variable. But that's NOT copying that's assignment (making a new pointer for the object location).

What is deep copying of objects then really if there are reference variables contained within the object you are trying to clone? Would using myObj2 = myObj.clone() clone all components within the object? Lets say if myObj contained other reference variables pointing to other object locations, would those reference variables also be cloned? So myObj2's internal reference variables would not be pointing to the same old object locations that pointers in myObj where pointing to.. I need clarity here to fully understand what cloning is all about.

Thank you in advance.

È stato utile?

Soluzione

I can give you an unsatisfying answer: the "clarity needed" will not be available. :)

The problem is, here are the first two sentences of the documentation for java.lang.Object.clone():

Creates and returns a copy of this object. The precise meaning of "copy" may depend on the class of the object. (emphasis added)

So it's up to the author of the class.

If you read the further documentation on clone(), it suggests that it should implement a deep copy (that copies all objects by value, rather than reference). For example:

Typically, this means copying any mutable objects that comprise the internal "deep structure" of the object being cloned and replacing the references to these objects with references to the copies.

But the default implementation of clone() does not do this:

Otherwise, this method creates a new instance of the class of this object and initializes all its fields with exactly the contents of the corresponding fields of this object, as if by assignment; the contents of the fields are not themselves cloned. Thus, this method performs a "shallow copy" of this object, not a "deep copy" operation.

So it depends on the class, and how the author interpreted the above semantics (assuming the author understood them).

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top