java Why ArrayIndexOutOfBoundsException用于2D数组,NPE用于1D数组
请帮助我理解为什么下面的代码抛出ArrayIndexOutOfBoundsException
Integer[][] arr1 = { { 1, 2, 3 }, { null }, { 7, 8, 9 } };
System.out.println("value = " + arr1[1][1].intValue());
为一维数组执行类似代码时抛出NullPointerException
Integer[] arr2 = { new Integer(1) , null , new Integer(2) };
System.out.println("value = " + arr2[1].intValue());
根据我的理解,我应该得到一维和二维阵列的NPE
# 1 楼答案
如果要在第一种情况下生成NullPointerException,则必须替换:
与:
使单个array1元素
arr1[1][1]
为空否则
arr1[1][1]
不会被实例化,您将得到ArrayIndexOutOfBoundsException
# 2 楼答案
这是因为索引
1
(arr1[1]
)处的数组是一个包含1null
的有效数组。如果选中arr1[1][0]
,它将返回null
,没有异常。您将得到一个ArrayIndexOutOfBoundsException
,因为它是一个有效数组,但在索引0
处结束如果您将代码切换为:
如果索引
arr1[1]
实际上是null
(而不是包含null
的数组),那么您将得到一个NullPointerException