gpt4 book ai didi

java - 没有初始大小的字符串数组给出空指针异常

转载 作者:搜寻专家 更新时间:2023-10-31 19:47:04 25 4
gpt4 key购买 nike

我只是在检查一些 OCJP 问题,并在字符串数组初始化和异常期间遇到了这种差异。

案例一

try {
String[][] b = new String[10][10]; // 1
System.out.println(b[0][0]); // 2
} catch (Exception e) {
System.out.println("Exception during array 'b' initialization");
e.printStackTrace();
}

案例二

try {
String[][] a = new String[10][]; // 3
System.out.println(a[0][0]); // 4
} catch (Exception e) {
System.out.println("Exception during array 'a' initialization");
e.printStackTrace();
}

第 2 行没有抛出任何异常,而第 4 行抛出空指针异常。不过,第 2 行确实将值输出为 null

在指定数组大小时和不指定数组大小时,java 的初始化默认值是否有区别?

最佳答案

这将 a 的类型设置为数组的数组:

String[][] a

当你写作时

String[][] a = new String[10][];

您初始化了外部数组,但没有创建内部数组,因此 a[0]null

当你写的时候

String[][] b = new String[10][10];

运行时也创建内部数组。它描述了here in the specification :

At run time, evaluation of an array creation expression behaves as follows:

If there are no dimension expressions, then there must be an array initializer.

A newly allocated array will be initialized with the values provided by the array initializer as described in §10.6.

The value of the array initializer becomes the value of the array creation expression.

Otherwise, there is no array initializer, and:

First, the dimension expressions are evaluated, left-to-right. If any of the expression evaluations completes abruptly, the expressions to the right of it are not evaluated.

Next, the values of the dimension expressions are checked. If the value of any DimExpr expression is less than zero, then a NegativeArraySizeException is thrown.

Next, space is allocated for the new array. If there is insufficient space to allocate the array, evaluation of the array creation expression completes abruptly by throwing an OutOfMemoryError.

Then, if a single DimExpr appears, a one-dimensional array is created of the specified length, and each component of the array is initialized to its default value (§4.12.5).

Otherwise, if n DimExpr expressions appear, then array creation effectively executes a set of nested loops of depth n-1 to create the implied arrays of arrays.

A multidimensional array need not have arrays of the same length at each level.

关于java - 没有初始大小的字符串数组给出空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16762154/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com