Java - 本机short上的操作总是返回int,为什么?如何?

时间:2016-06-09 09:16:30

标签: java boxing

我目前正在使用short,但短片之间的所有操作都会给我int。我知道Java不提供短文字,因此在声明/分配新的短变量时需要强制转换。

但为什么标准操作(+ - / *)会产生int? 是因为Java自动装箱机制吗?

例子(JDK 1.8):

private short prepareValue(short value)
{
    // here: no literal, so cast, but cast is not required for test?
    short sign = (value < 0) ? (short)-1 : (short)1;

    // here: short*short=int, so casting the result
    short absValue = (short)(value * sign);

    // here: the function returns a short, but same problem as before
    value = (short)(myFunctionOnlyOnPositive(absShort) * sign);

    // ... more things
    return value;
}

我看了Conversions and Contexts,但我没有找到任何帮助。甚至关于Short的文档也没有帮助(此时我必须愚蠢或其他什么)。那么有人可以向我解释为什么Java会假设short * short = int

0 个答案:

没有答案