Welcome to the Java Programming Forums

The professional, friendly Java community. 21,500 members and growing!

The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.

>> REGISTER NOW TO START POSTING

Thread: 2D array shallow and deep cloning

1. 2D array shallow and deep cloning

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.'

```Point [][]a;
Point [][]b;```

And this is what the answer is but I am not sure which part is the shallow copy and which is deep:
```b = (Point[][]) a.clone();
for(int i=0;i<a.lenght;i++)
{
b[i] = (Point[]) a[i].clone();
for(int j=0;j<b.lenght;j++)
b[i][j] = (Point)b[i][j].clone();
}```

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

3. Re: 2D array shallow and deep cloning

Yes it is - I need to get an answer since this is drive me insane.

5. Re: 2D array shallow and deep cloning

Thank you for your feedback - I noticed that article but I was looking more at the clone() method.
I read it few times but I am still not clear.