我正在使用Java中的位移,并使下面的代码按预期工作:
final byte value = 1;
final int shift = 1;
byte result = value << shift;
Run Code Online (Sandbox Code Playgroud)
这会产生2预期的值.但是,如果我尝试将其提取到如下方法中:
private void shiftAndCheck(final byte value, final int shift) {
byte result = value << shift;
}
Run Code Online (Sandbox Code Playgroud)
这会导致编译错误:
java: incompatible types: possible lossy conversion from int to byte
Run Code Online (Sandbox Code Playgroud)
问题是导致失败的方法是什么?
由于value和shift是此代码片段中的编译时常量:
final byte value = 1;
final int shift = 1;
byte result = value << shift;
Run Code Online (Sandbox Code Playgroud)
然后编译器内联它们的值(用 的实际值替换所有出现的value和),并可以在运行时之前验证 的结果不会导致任何精度损失。shift1value << shift
同时,对于第二个片段:
private void shiftAndCheck(final byte value, final int shift) {
byte result = value << shift;
}
Run Code Online (Sandbox Code Playgroud)
编译器没有证据shift表明该值,这不会导致精度损失,这就是引发编译错误的原因。
如果在这种情况下可以进行编译,那么您就可以执行shiftAndCheck(1, 32);会导致byte类型溢出的操作。
| 归档时间: |
|
| 查看次数: |
44 次 |
| 最近记录: |