jQuery in Action, 2nd edition*
The moose likes Beginning Java and the fly likes 2D array shallow and deep cloning Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "2D array shallow and deep cloning" Watch "2D array shallow and deep cloning" New topic
Author

2D array shallow and deep cloning

Adrian Vasile
Greenhorn

Joined: Oct 13, 2013
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

Joined: Apr 20, 2011
Posts: 237
    
    1

inb4 array of array corrections
Adrian Vasile
Greenhorn

Joined: Oct 13, 2013
Posts: 3
Can you be more specific? I am not sure what do you mean.
manish ghildiyal
Ranch Hand

Joined: Jan 12, 2013
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
Sheriff

Joined: Oct 13, 2005
Posts: 39409
    
  28
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
Adrian Vasile
Greenhorn

Joined: Oct 13, 2013
Posts: 3
I have a better idea now - thank you everyone for your time and effort!.
AV
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39409
    
  28
You're welcome
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: 2D array shallow and deep cloning