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

标签 java arrays nullpointerexception

我只是在检查一些 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/

相关文章:

java.lang.SecurityException AWSCredentialsProvider 签名者信息不匹配

java - JVM DNS 缓存和 DNS 循环

c - 为什么数组变量等于它的地址?

Javascript - 嵌套数组排序无法按预期工作

java - 使用 Maven 构建 Liferay 项目时出现 NullPointerException

spring - Autowiring LinkedBlockingQueue 时出现空指针异常

java - Android 中的倒计时器不同步?

java - 创建类路径资源 [EnableWebMvcConfiguration.class] 中定义的名称为 'resourceHandlerMapping' 的 bean 时出错

javascript - 如何将数组的所有项值设置为0?

java - BufferedImage 数组的 NullPointerException