简体   繁体   中英

modifying the copied 2d array in java

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?

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

Try this:

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);
}

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);

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

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
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM