gpt4 book ai didi

java - 为什么空数组引用的数组访问表达式不抛出 NullPointerException?

转载 作者:搜寻专家 更新时间:2023-10-31 20:00:13 24 4
gpt4 key购买 nike

考虑以下代码:

int[] r = null;
r[0] = 1 % 0;

我预计这会抛出一个NullPointerException:根据JLS Sec 15.7.1 :

The left-hand operand of a binary operator appears to be fully evaluated before any part of the right-hand operand is evaluated.

= 是一个二元运算符(在 JLS Sec 15.2 中显示 - JLS Sec 15.26 描述了赋值运算符),完全计算左侧操作数将导致 NullPointerException。但是,将抛出 ArithmeticException,表示在完全计算左侧操作数之前计算右侧操作数。

为什么?

最佳答案

the simple assignment operator的规范描述了这种行为:

...

If the left-hand operand is an array access expression (§15.10.3), possibly enclosed in one or more pairs of parentheses, then:

  • First, the array reference subexpression of the left-hand operand array access expression is evaluated. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason; the index subexpression (of the left-hand operand array access expression) and the right-hand operand are not evaluated and no assignment occurs.

正常完成。

  • Otherwise, the index subexpression of the left-hand operand array access expression is evaluated. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason and the right-hand operand is not evaluated and no assignment occurs.

正常完成。

  • Otherwise, the right-hand operand is evaluated. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason and no assignment occurs.

这突然完成,并出现 ArithmeticException

  • Otherwise, if the value of the array reference subexpression is null, then no assignment occurs and a NullPointerException is thrown.

这永远不会执行。

因此,在第 15.7.1 节的引述中似乎存在不一致 - 或者过度简化,至少。


有趣的是,复合赋值运算符没有观察到相同的行为,例如

int[] arr = null;
arr[0] += 1 % 0;

确实产生NullPointerException

JLS Sec 15.26.2描述这个。不过,这也许并不令人惊讶,因为:

A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T) ((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once.

换句话说,这段代码(大致)等同于:

arr[0] = arr[0] + 1 % 0;

因此 NullPointerException 发生在评估简单赋值的右手操作数时。

关于java - 为什么空数组引用的数组访问表达式不抛出 NullPointerException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42854455/

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