programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering OS Languages Paradigms IDEs Build Tools Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# 2D array shallow and deep cloning

Greenhorn
Posts: 3
Hello everyone - I am new to Java and trying to understand.
We have an assignment and we have to create a shallow and deep clone using a for loop.
Here is what we have - 'suppose that a is 2D point array but you don't have any idea what data or how many rows or columns it is actually in array a. Write the code which only uses clone in a for loop to make a shallow and a deep clone of a in b using only the references to a and b.'

And this is what the answer is but I am not sure which part is the shallow copy and which is deep:

Which one is shallow and which one is deep?
I though that
b = (Point[][]) a.clone();
is the shallow but now I am all confused.

Thank you.
AV

Joel Christophel
Ranch Hand
Posts: 250
1
inb4 array of array corrections

Greenhorn
Posts: 3
Can you be more specific? I am not sure what do you mean.

manish ghildiyal
Ranch Hand
Posts: 136
b[i] = (Point[]) a[i].clone();
This line of code is shallow copying as calling clone on an array just copies the references in cells.

for(int j=0;j<b.lenght;j++)
b[i][j] = (Point)b[i][j].clone();

Here it seems you are trying to do deep copying but I guess you need to implement
clone method for Point class accordingly.

Manish

Campbell Ritchie
Marshal
Posts: 56534
172
• 1
Welcome to the Ranch
I think what the cryptic post was supposed to mean is that you do not have a 2D array because Java does not support them. You have an array of arrays.
Why are you casting the result of the clone() method? That may be necessary only for the (Point) cast.
The second code block does a deep clone on the array of arrays and also clones each of the Point objects. That should work if Point means java.awt.Point. A poorly‑designed class if ever I saw one