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/