0

I am trying to copy a 2d array of ints to another,such that the original remains unaffected when copied array is modified

            int[][] t3 = new int[][]{
            {1,2,3},
            {0,4,6},
            {7,8,9}
        };
        show(t3);

        int[][] t4 = new int[t3.length][t3[0].length];
        System.arraycopy(t3, 0,t4 ,0, t3.length-1);
        show(t4);

        t3[0][0]=99;
        show(t3);
        show(t4);

However,the original gets modified here

t3
1 2 3 
0 4 6 
7 8 9 

t4
1 2 3 
0 4 6 
0 0 0 

t3 modified
99 2 3 
0 4 6 
7 8 9 

t4
99 2 3 
0 4 6 
0 0 0 

I tried clone() ,still the behaviour is the same

Why is this? Any idea how to keep the original unmodified?

4

5 回答 5

1
for(int i = 0; i < t3.length; i++)
    t4[i] = t3[i].clone();

Try this:

于 2013-03-11T08:41:00.893 回答
1

You are just coping 1d array references to your new array t4. That is why your reference t4 still points to your old 1d arrays.

You should use a loop to replace 'deeper' arrays:

for (int i = 0; i < t3.length; i++) {
    System.arraycopy(t3[i], 0, t4[i], 0, t3[0].length);
}
于 2013-03-11T08:41:47.237 回答
1

You need to copy each array of your 2d array.

Using Arrays.copyOf(int[], int):

int[][] t4 = new int[t3.length][];
for(int i = 0 ; i < t3.length ; ++i) {
    t4[i] = Arrays.copyOf(t3[i], t3[i].length);
}
show(t4);
于 2013-03-11T08:41:51.230 回答
0

Just use this method

public static int[][] produceAcopy2DArray(int[][] original) {
    int [][] copied = new int[original.length][];
    for(int i = 0; i < original.length; i++)
        copied[i] = original[i].clone();
    return copied;
}  

Then call it where you like as

t4 = produceAcopy2DArray(t3);  

Then you will keep the original unmodified as you need

于 2013-03-11T08:51:20.753 回答
0

The copy utilities in Java will not copy a multidimensional array. You must iterate over the array and assign the values into a new array.

 public static void main(String[] args) {
            int[][] t3 = new int[][] { { 1, 2, 3 }, { 0, 4, 6 }, { 7, 8, 9 } };

            int[][] t4 = new int[t3.length][t3[0].length];

            for (int x = 0; x < t3.length - 1; x++) {
                for (int y = 0; y < t3[x].length - 1; y++) {
                    t4[x][y] = t3[x][y];
                }
            }

            t4[0][0] = 99;
            System.out.println(t3[0][0]); //Prints 1
            System.out.println(t4[0][0]); //Prints 99
        }
于 2013-03-11T08:53:32.807 回答