简体   繁体   English

为什么 ArrayIndexOutOfBoundsException 用于 2D 数组而 NPE 用于 1D 数组

[英]Why ArrayIndexOutOfBoundsException for 2D Array and NPE for 1D array

Please help me to understand why below code throws ArrayIndexOutOfBoundsException请帮助我理解为什么下面的代码会抛出 ArrayIndexOutOfBoundsException

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

Similar code when executed for single dimensional array throws NullPointerException.对一维数组执行类似的代码时会抛出 NullPointerException。

Integer[] arr2 = { new Integer(1) , null , new Integer(2) };
System.out.println("value = " + arr2[1].intValue());

In my understanding I should get NPE for both 1D and 2D array.据我了解,我应该为一维和二维阵列获得 NPE。

It's because the array at index 1 ( arr1[1] ) is a valid array with 1 null in it.这是因为索引1 ( arr1[1] ) 处的数组是一个有效数组,其中包含 1 null If you checked arr1[1][0] it would return null without an exception.如果您检查了arr1[1][0] ,它将毫无例外地返回null You're getting an ArrayIndexOutOfBoundsException because it's a valid array but ends at index 0 .你得到一个ArrayIndexOutOfBoundsException因为它是一个有效的数组,但在索引0处结束。

If you switched the code to:如果您将代码切换为:

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

in which index arr1[1] is actually null (instead of an array with null in it), then you would get a NullPointerException .其中索引arr1[1]实际上是null (而不是其中包含null的数组),那么你会得到一个NullPointerException

If you want to produce a NullPointerException in the first case, you have to replace:如果要在第一种情况下产生 NullPointerException,则必须替换:

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

with:和:

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

to make the individual array1 element arr1[1][1] null.制作单个array1元素arr1[1][1] null。

Otherwise arr1[1][1] is not instantiated and you get ArrayIndexOutOfBoundsException .否则arr1[1][1]不会被实例化,你会得到ArrayIndexOutOfBoundsException

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM