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.
在决定是否应在编译时执行某项检查时,编译器设计团队会考虑新功能的成本和收益.由于编译时检查不会取代运行时检查,但除了它之外还会执行,因此额外的好处是微不足道的.但是,这并不意味着该功能不应该在编译器的未来版本中实现,只是语言设计者没有将其优先级设置得足够高以便现在实现.
标签:java,arrays,initialization
来源: https://codeday.me/bug/20190607/1195113.html