根据我对 Java 中二维数组的理解,我知道它可以像这样初始化:
int a[][] = new int[3][1];
3->代表行
1->代表col
如图所示:
我的问题是为什么当我使用它时:
int a[][] = new int[3][1];
a[4] =new int[]{1,2,3,3,4};
System.out.print(a[4][4]);
它给出:
ArrayIndexOutOfBoundsException: which is the right behavior where a[4] is out of index because of the size which is 3.
但是使用它不会给出任何异常:
int a[][] = new int[3][1];
a[1] = new int[]{1,2,3,3,4};
a[2] = new int[]{4,5};
System.out.print(a[1][4]);
即使是1 [4] 确实存在于初始化中,但它超出了索引,因为 col 的大小等于 1。
任何想法!
谢谢。
最佳答案
当你分配
a[1] = new int[]{1,2,3,3,4};
a[1]
现在引用一个包含 5 个元素的 int 数组,所以 a[1][4]
是有效的。与最初 a[1]
引用 1 个元素的 int 数组无关紧要,因为在赋值之后,a[1]
引用一个新数组。
您应该记住,二维数组实际上是数组的数组(即元素类型为数组的数组)。因此,您可以将新的内部数组分配给外部数组的任何索引。
关于java - 为什么我在二维数组上没有得到 ArrayIndexOutOfBoundsException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32473578/