java - 为什么数组的负大小不是编译错误而是抛出 java.lang.NegativeArraySizeException

标签 java arrays initialization

java 不允许初始化一个负数的数组。例如:

int[] arr = new int[-1];

如果这是已知的,为什么它抛出 NegativeArraySizeException 而不是编译错误?只是想知道为什么 java 决定在运行时抛出它,而在编译时就知道它会失败。

最佳答案

只有在将大小指定为常量表达式的情况下,才能在编译时执行此检查。但是,Java 语言规范要求在运行时完成此检查:

15.10.2 Run-Time Evaluation of Array Creation Expressions

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

[...]

  • 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.

在决定是否应在编译时执行某项检查时,编译器设计团队会考虑新功能的成本和 yield 。由于编译时检查不会取代运行时检查,而是会在运行时检查之外执行,因此增加的好处是微不足道的。然而,这并不意味着该功能不应在未来版本的编译器中实现,只是语言设计者没有将其优先级设置到足以立即实现的程度。

关于java - 为什么数组的负大小不是编译错误而是抛出 java.lang.NegativeArraySizeException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49009638/

相关文章:

java - ww SimpleDateFormat 的奇怪行为

java - 尝试使用 Java 运行 PL/SQL 脚本

java - 如何使用多线程来完成一项工作?

c - 将可变长度二维数组传递给函数

.net - 在 .NET 中,Array 只扩展了 IEnumerable,那么当 foreach 循环经过值类型数组时,是否会有装箱和拆箱?

python - 修复了带有线程锁的 strptime 异常,但会减慢程序速度

java - 密码锁辅助

javascript - 如何从元素集中获取 id 并保存在数组中?

c++ - 为什么不能通过直接初始化语法来初始化类数据成员?

c - 为什么我运行c程序后总是得到0?请帮助我