我正在初始化一个二维数组,同时指定行数和列数。如果我插入的项目多于初始化中声明的数量,我预计它会抛出错误,但代码运行正常。
static void arrayChecks(){
int[][] arr = new int[2][2];
arr[0] = new int[]{1,2};
arr[1] = new int[]{3,4,5}; //adding 3 items to a 2-column row. No exception thrown
//arr[2] = new int[]{6,7}; //throws ArrayIndexOutOfBoundsException as expected.
for(int[] a : arr){
for(int i : a){
System.out.print(String.valueOf(i));
}
}
//output = 12345
}
最佳答案
Java 不像某些语言那样支持二维数组。它只是将它们视为数组引用的数组。这些内部数组可以重新分配给任意长度的另一个数组。
int[][] arr = new int[2][2];
的脱糖版本是:
int[][] arr = new int[2][];
arr[0] = new int[2];
arr[1] = new int[2];
您可以将 arr[1]
重新分配给您想要的任何 int[]
。 Java 允许交错数组,其中每个内部数组的长度不同。
关于java - 为什么这个 Java 二维数组不抛出 IndexOutOfBoundException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45443305/