This week's book giveaway is in the Performance forum.
We're giving away four copies of The Java Performance Companion and have Charlie Hunt, Monica Beckwith, Poonam Parhar, & Bengt Rutisson on-line!
See this thread for details.
Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

2D array shallow and deep cloning

 
Adrian Vasile
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Chrome Eclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
inb4 array of array corrections
 
Adrian Vasile
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can you be more specific? I am not sure what do you mean.
 
manish ghildiyal
Ranch Hand
Posts: 136
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 49466
64
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a better idea now - thank you everyone for your time and effort!.
AV
 
Campbell Ritchie
Sheriff
Pie
Posts: 49466
64
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're welcome
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic