How to clone a multidimensional array in java? [duplicate]

你离开我真会死。 提交于 2019-11-27 02:04:54

When the above code is run, arrayMaster changes as well as arrayChanges, contrary to my intentions.

The line

static private int[][] arrayChanges = arrayMaster;

is the culprit. This line makes arrayChanges and arrayMaster point to the same object, so a change to either one is visible when you access the object from either.

EDIT: What happens whenever you clone one dimension of a multidimensional array

As Eric Lippert explains, an array is conceptually a list of variables. If you just assign another variable to point to the same array a la static private int[][] arrayChanges = arrayMaster;, you haven't changed the set of variables at all. You haven't created any new variables except for arrayChanges, so you haven't gotten more memory from the operating system/JVM, so any change you make to arrayMaster is applied to arrayChanges and vice versa.

Now let's look at a two-dimensional array. In Java, a two-dimensional array is a list of variables that happens to have the property that each one of these variables refers to a one-dimensional array. So, whenever you clone a two-dimensional array, you create a new list of variables, each pointing in the same place that the old variables pointed in. So, you have gained a little in that you can safely write arrayChanges[0] = new int[10] without affecting arrayMaster, but as soon as you start referencing arrayChanges[i][j] you are still referencing the same second-level arrays that arrayMaster references. What you really want in order to deep-copy a two-dimensional array of ints is

public static int[][] deepCopyIntMatrix(int[][] input) {
    if (input == null)
        return null;
    int[][] result = new int[input.length][];
    for (int r = 0; r < input.length; r++) {
        result[r] = input[r].clone();
    }
    return result;
}

To those who may look at this answer in the future: yes, it is better replace int with T here and make the method generic, but for this purpose a more concrete deep copy method is simpler to explain well.

clone does a "shallow" copy. That is, the outermost array is duplicated, but the values stored in it are unchanged. So if you have A1 = { B1, B2, B3 } and clone that into A2, A2's initial contents will be { B1, B2, B3 }. If you change A1 to { C1, B2, B3 } then A2 will remain unchanged, but if you change the contents of B1 (without replacing it) then A2 will "see" that change.

To accomplish what you want you must loop through the outer array and clone the elements of that outer array (which are the inner arrays).

Pidgin Java:

int[][] A2 = A1.clone();
for (int i = 0; i < A2.length; i++) {
    A2[i] = A2[i].clone();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!