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!

Embed101
  • 152
  • 2
  • 3
  • 12

1 Answers1

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

Community
  • 1
  • 1
mikeslattery
  • 4,039
  • 1
  • 19
  • 14