St.Antario
St.Antario

Reputation: 27395

Understanding deepCopy concept

I'm reading about the so called UserType in Hiberante that declares the deepCopy(Object) method. Authors suggest we use the following implementation for immutable classes:

Because MonetaryAmount is an immutable class, the deepCopy() method returns its argument.

Why? I thought the deepCopy implementing as follows:

public Object deepCopy(Object value) throws HibernateException {
    return value;
}

is actually a shallow-copy. What did I miss?

Upvotes: 0

Views: 109

Answers (2)

Florian Schaetz
Florian Schaetz

Reputation: 10652

If you return the same object you put into a method, then that's not any copy at all, neither swallow nor deep. A shallow copy would be if you copied all the references in the given object to a new one. A deep copy is when you dereference everything and create copies of all the child, etc. objects of your original.

Example:

MyObject has a reference to a Calendar object.

Shallow Copy to "MyCopy":

MyCopy (a new object, not the same (==) as MyObject) gets a reference to the same Calendar object.

Problem: If I now modify the Calendar of "MyCopy", the Calendar of "MyObject" will change, too, because it is the same one.

Deep Copy:

MyCopy gets a new Calendar which is a complete (itself deep) copy of the MyObject Calendar.

Advantage: If I now modify the Calendar of MyCopy, nothing changes for the one of MyObject.

If you have an immutable object, there is no need to deep copy it, because you can simply use the same object everywhere - it cannot be modified (thus immutable), so that is perfectly safe - and fast.

see also Wikipedia

Upvotes: 1

Codebender
Codebender

Reputation: 14471

Immutable object's cannot change it's state. So it doesn't matter if you return the same object. Since no modification can be done to it anyway. So it actually acts like a deepCopy when there is no copy at all.

Let's take an example of String.

String s1 = "hello";
String s2 = new String(s1);
String s3 = s1;

It doesn't matter what operation you perform on any of the variables, it's not going to affect the other 2.

Upvotes: 1

Related Questions