如何使用[] [] []结构复制和深度复制muldtidimesional数组

时间:2015-12-10 09:39:50

标签: java android arrays multidimensional-array

我有一个多维数组=> mda [][][]。我想做的是复制 mda [0][all][all]mda [ 1 ][][],然后对新创建的mda[ 1 ][][]部分进行一些操作。 我在互联网上检查了堆栈overflaw和所有其他教程,并遇到了[][]结构而不是[][][]结构的教程。我会接受链接作为答案,只要他们专门解决问题,我不寻求长迭代和那种解决方案。可能我正在寻找clone()copy()类型的函数解决方案。 提前谢谢

1 个答案:

答案 0 :(得分:0)

在Java中深度复制(这就是你想要的)多维数组的唯一方法是迭代。

所以在你的情况下,你最终会得到这样的东西:

public static void main(String[] args) {
    // First we create the mda:
    String[][][] mda = new String[2][][];

    // Now we fill the mda[0][0][0] with 8
    mda[0] = new String[][] { {"8"} };

    // We make a deepCopy of mda[0] and put it in mda[1]:
    mda[1] = deepCopy(mda[0]);

    // Now we change the value of mda[1][0][0]:
    mda[1][0][0] = "42";

    // And here we show it is truly a copy, mda[0][0][0] isn't changed:
    System.out.println(mda[0][0][0]);
    System.out.println(mda[1][0][0]);
}

private static String[][] deepCopy(String[][] input) {
    String[][] output = new String[input.length][];
    for(int index = 0; index < input.length; index++) {
        output[index] = input[index].clone();
    }
    return output;
}

输出将是一个真实的副本:

8
42