Kev*_*sen 4 java arrays instantiation multidimensional-array
使用以下 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?)
Run Code Online (Sandbox Code Playgroud)
所以,我的问题是,为什么仅分配多维数组的第一个大小就足够了?我认为你总是必须分配一个大小,甚至是为多维数组的每个单独的数组部分分配一个大小,但今天我发现这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?)
Run Code Online (Sandbox Code Playgroud)
我现在有点困惑,如果有人知道的话希望得到一些澄清。
编辑/半解决方案:
好的,我知道为什么第一部分有效:
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
Run Code Online (Sandbox Code Playgroud)
唯一需要回答的是:
int[][][] array10 = new int[2][][2]; // Incorrect?? (Or is this correct?)
Run Code Online (Sandbox Code Playgroud)
是否有效。
首先简单来说:二维数组是数组的数组。Java中的数组是对象。仅定义第一个大小就会创建一个给定大小的数组,它可以存储其他数组,但此时这些数组仍然为空。所以在使用它之前,你需要调用类似的东西array1[0] = new int[5],否则你会得到一个 NullPointerException。对于多维数组,这也相应适用。
理论上,所有“内部”数组实际上都可以具有不同的长度。所以你可以写这样的东西array1[0] = new int[1]; array1[1] = new int[4];:
关于你的最后一个问题:这是无效的,Java编译器会说“无法在空维度后指定数组维度”。这是因为第二级未指定,因此是第一级数组中的空对象,因此无法在这些空数组上指定维度。