Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/365.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 为什么二维阵列使用ArrayIndexOutOfBoundsException,而一维阵列使用NPE_Java_Arrays_Exception_Indexoutofboundsexception - Fatal编程技术网

Java 为什么二维阵列使用ArrayIndexOutOfBoundsException,而一维阵列使用NPE

Java 为什么二维阵列使用ArrayIndexOutOfBoundsException,而一维阵列使用NPE,java,arrays,exception,indexoutofboundsexception,Java,Arrays,Exception,Indexoutofboundsexception,请帮助我理解为什么下面的代码抛出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 ,

请帮助我理解为什么下面的代码抛出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());

据我所知,我应该得到1D和2D数组的NPE。

这是因为索引
1
arr1[1]
)处的数组是一个包含1
null
的有效数组。如果选中
arr1[1][0]
,它将返回
null
,没有异常。您将获得一个
ArrayIndexOutOfBoundsException
,因为它是一个有效数组,但以索引
0
结尾

如果您将代码切换为:

Integer[][] arr1 = { { 1, 2, 3 }, null, { 7, 8, 9 } };

如果索引
arr1[1]
实际上是
null
(而不是包含
null
的数组),那么您将得到
NullPointerException
如果您想在第一种情况下生成NullPointerException,您必须替换:

Integer[][] arr1 = { { 1, 2, 3 }, { null }, { 7, 8, 9 } };
System.out.println("value = " + arr1[1][1].intValue());
与:

使单个数组1元素
arr1[1][1]
null


否则,
arr1[1][1]
不会实例化,您会得到
ArrayIndexOutOfBoundsException

在第一种情况下,
arr1[1]
{null}
,一个包含一个元素的数组。因此
arr1[1][1]
是一个索引错误。在第二种情况下,
arr2[1]
为空,因此尝试对其调用方法会产生NPE。如果尝试使用
arr1[1][0]
访问空元素,则会得到NPE。@GriffeyDog只是为了澄清,通过
arr1[1][0]
访问
null
不会导致
NPE
。但是,在我们成功访问它之后,
arr1[1][0]。intValue()
将变为
null.intValue()
,并且该调用将抛出NPE。@Pshemo这就是我的注释的目的,访问该元素上的
intValue
方法。我的观点是
null
元素位于索引0,而不是1。
Integer[][] arr1 = { { 1, 2, 3 }, { null, null }, { 7, 8, 9 } };
System.out.println("value = " + arr1[1][1].intValue());