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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值