java – 为什么空数组引用的数组访问表达式不会抛出NullPointerException?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了java – 为什么空数组引用的数组访问表达式不会抛出NullPointerException?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2180字,纯文字阅读大概需要4分钟。
内容图文
![java – 为什么空数组引用的数组访问表达式不会抛出NullPointerException?](/upload/InfoBanner/zyjiaocheng/797/5f987ff31c8e4138945f4420df2be7ef.jpg)
请考虑以下代码:
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 toE1 = (T) ((E1) op (E2))
, whereT
is the type ofE1
, except thatE1
is evaluated only once.
换句话说,这段代码(大致)相当于:
arr[0] = arr[0] + 1 % 0;
因此在评估简单赋值的右手操作数时会发生NullPointerException.
内容总结
以上是互联网集市为您收集整理的java – 为什么空数组引用的数组访问表达式不会抛出NullPointerException?全部内容,希望文章能够帮你解决java – 为什么空数组引用的数组访问表达式不会抛出NullPointerException?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。