1

I have been at this little project and i spend like 20 hours solving (without any luck or results) a major problem in the code. Now i am at the point that i found out that the real problem is that the copy() function does not properly work.

What am i doing wrong?

This is the example i made of the specific problem:

package cloneobject; import java.util.Arrays; public class CloneObject { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here clone(new int[3][3]); } public static void clone(int[][] x) { int[][] y = (int[][]) x.clone(); System.out.println("x="); PrintFieldImage(x); System.out.println("y="); PrintFieldImage(y); x[1][1] = 3; System.out.println("x="); PrintFieldImage(x); System.out.println("y="); PrintFieldImage(y); y[2][2] = 4; System.out.println("x="); PrintFieldImage(x); System.out.println("y="); PrintFieldImage(y); } public static void PrintFieldImage(int[][] field) { if (field != null) { int x; for (x = 0; x < field.length; x++) { System.out.println(Arrays.toString(field[x])); } } else { System.out.println("no field!"); } } } 

and this is the result:

run: x= [0, 0, 0] [0, 0, 0] [0, 0, 0] y= [0, 0, 0] [0, 0, 0] [0, 0, 0] x= [0, 0, 0] [0, 3, 0] [0, 0, 0] y= [0, 0, 0] [0, 3, 0] [0, 0, 0] x= [0, 0, 0] [0, 3, 0] [0, 0, 4] y= [0, 0, 0] [0, 3, 0] [0, 0, 4] BUILD SUCCESSFUL (total time: 0 seconds) 

Now i wish let x contain 3, and y contain 4.

Plz help!

2
  • 2
    Two dimensional arrays are really arrays of arrays, so that each row of the array is its own reference variable. You will need to copy these as well into new arrays to avoid this problem, a deep copy. Commented Jan 29, 2013 at 19:50
  • stackoverflow.com/q/5617016/422353 Commented Jan 29, 2013 at 19:52

1 Answer 1

7

clone() only will do a shallow clone. You are cloning a 2D array; an array of arrays. Only the top level array will be cloned. If you want to do a deep clone, you'll have to use ol' fashioned for loop(s).

int[][] y = new int[x.length][]; for(int i=0; i<x.length; i++) { y[i] = x[i].clone(); } 

See also copy a 2d array in java

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.