Question

I read this post today about deep copying and had a few questions:

In the first code, the author says adding an (integer) object to a clone does not appear in the original. Why is this so? As I understand, cloning basically creates an object with the same references to objects as the original.

Why isn't a change in the clone reflected back in the original?

Doesn't clone share the same reference as the Original?

Was it helpful?

Solution 2

When you do a clone of an Object 'A', you are creating a new Object 'B' (with the same references to objects) but in a different memory address. Thus, when you modify the object 'A' you are not accessing the same memory address of the Object 'B'. Therefore, changes in the clone do not reflect back in the original object and vice-versa.

Shallow Copy

Generally, the clone method of an object, creates a new instance of the same class and copies all the fields to the new instance and returns it. This is nothing but shallow copy. Object class provides a clone method and provides support for the shallow copy. It returns ‘Object’ as the type and you need to explicitly cast back to your original object.

Deep Copy

When you need a deep copy then you need to implement it yourself. When the copied object contains some other object its references are copied recursively in the deep copy. When you implement a deep copy be careful as you might fall for cyclic dependencies. If you don’t want to implement deep copy yourself then you can go for serialization. It does implement deep copy implicitly and gracefully handling cyclic dependencies.

(source about the information)

Here an illustrative example:

Shallow

Before Copy Shallow Copying Shallow Done

Deep:

Before Copy Deep Copying
(source: wikimedia.org)

Deep Done

OTHER TIPS

The whole purpose of a clone is to be different than the original - so changes in the clone are not reflected in the original. Otherwise, you could just use simple assignment as opposed to cloning.

e.g.

MyClass a = new MyClass();  // some cloneable class

MyClass b = a;  // not a clone, changes to `b` will affect in `a`
                // assignment duplicates the reference
    -or-

MyClass b = a.clone();  // clone, changes to `b` will not affect in `a`
                        // clone duplicates the object

There is actually a Wikipedia article on Java cloning here.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top