Last Updated: September 29, 2021
·
2.235K
· devtripper

Cloning Java objects

The process of cloning an object means create an exact copy of an object in memory. Ok, its not so simple. In fact, just saying something like “(object) a is a clone of (object) b” could be dangerously imprecise. So, lets analyze it.

Picture

Basically, there are two types of cloning:

  • Shallow copy

  • Deep copy

What’s the difference between these two cloning mechanisms? First, we have to think an object as a tree of references. For example, we could have an Employee object, that HAS A: Billing, a PersonalInfo references, and a String member named age. Furthermore, Billing object is composed by references to Taxes and BaseRate references. As you can see, an Employee object is, in a way, a tree of references to all the mentioned objects.

When we talk about shallow copy, what we are doing is to create a new instance of the type of object to be cloned, and its member values. Following Employee example, the cloned employee object will have age member with the same value of original employee. Plus, and here is the trick, references of cloned employee will be the same references of original employee. So, if after cloning employee we change something in the cloned employee, that change will affect original one. Simply because both objects contains the same references. As you can see, shallow copy of an object has its limitations. And that’s where deep copy comes into scene.

Deep copy means creating the whole tree of references of the original object. So, using deep cloning, we could change values in Billing object of the cloned object without affecting the original one. Simply because they are different objects. Now, we have two Billing objects in memory, one for each employee object.
There are multiple ways to implement deep copy in Java. I will present a simple solution, using serialization, implemented by Apache:

Picture

To use it, simply invoke deepClone method, passing as parameter the object that you want to clone, and it will create a copy of it. Internally, this method will serialize the original object and deserialize it in order to force the full recreation of the new cloned object.

As you can imagine, using serialization and deserialization of objects its not free in terms of performance, so it could affect it if we use this cloning method. There are other ways (a little more complex, but far more efficient to deal with deep copy of objects. Ill post additional methods of deep cloning in a near future. Stay connected!

3 Responses
Add your response

Nice article. It is one of commonly newbie (esp Java) mistakes.

over 1 year ago ·

For God's sake, why do you want to clone an object!!

over 1 year ago ·

A good reason to use cloning is if setting up the state of an object is harder/ expensive and you just need the copy to change the state for some reason ;)

over 1 year ago ·