【发布时间】:2014-11-27 14:21:24
【问题描述】:
使用以下 Java 示例:
int[] array1 = new int[]; // Incorrect, since no size is given
int[] array2 = new int[2]; // Correct
int[][][] array3 = new int[][][]; // Incorrect, since no size is given
int[][][] array4 = new int[2][2][2]; // Correct
int[][][] array5 = new int[2][][]; // Correct (why is this correct?)
那么,我的问题是,为什么只分配多维数组的第一个大小就足够了?我以为你总是必须分配一个大小,甚至是多维数组的每个单独的数组部分,但今天我发现array5 也是 Java 的正确方法。现在我只是想知道为什么。有人可以举一些例子说明为什么这适用于多维数组和/或背后的原因吗?
另外,我想以下内容也适用:
int[][][] array6 = new int[][2][]; // Incorrect
int[][][] array7 = new int[][][2]; // Incorrect
int[][][] array8 = new int[][2][2]; // Incorrect
int[][][] array9 = new int[2][2][]; // Correct
int[][][] array10 = new int[2][][2]; // Incorrect?? (Or is this correct?)
我现在有点困惑,如果有人知道,我想澄清一下。
编辑/半解决方案:
好的,我知道为什么第一部分有效:
int[][] array = new int[2][];
array[0] = new int[5];
array[1] = new int[3];
// So now I have an array with the following options within the array-index bounds:
// [0][0]; [0][1]; [0][2]; [0][3]; [0][4]; [1][0]; [1][1]; [1][2]
// It basically means I can have different sized inner arrays
唯一需要回答的是:
int[][][] array10 = new int[2][][2]; // Incorrect?? (Or is this correct?)
是否有效。
【问题讨论】:
标签: java arrays multidimensional-array instantiation