4

这是 Eclipse 中的错误吗?

声明短变量时,编译器将整数文字视为短变量。

// This works
short five = 5;

然而,当将整数文字作为短参数传递时,它并没有做同样的事情,而是产生了一个编译错误:

// The method aMethod(short) in the type Test is not applicable for 
// the arguments (int)
aMethod(5); 

它清楚地知道整数文字何时超出短整数范围:

// Type mismatch: cannot convert from int to short
    short notShort = 655254

-

class Test {
    void aMethod(short shortParameter) {
    }

    public static void main(String[] args) {
        // The method aMethod(short) in the type Test is not applicable for 
        // the arguments (int)
        aMethod(5); 

      // the integer literal has to be explicity cast to a short
      aMethod((short)5);

      // Yet here the compiler knows to convert the integer literal to a short
      short five = 5;
      aMethod(five);


      // And knows the range of a short
      // Type mismatch: cannot convert from int to short
        short notShort = 655254
    }
}

参考:Java 原始数据类型

4

1 回答 1

8

这是因为在调用方法时,只授权原始的扩大转换,而不是原始的缩小转换(int -> short 是)。这是在JLS #5.3中定义的:

方法调用上下文允许使用以下之一:

  • 身份转换(§5.1.1)
  • 扩大的原始转换(§5.1.2)
  • 扩大参考转换(§5.1.5)
  • 一个装箱转换(第 5.1.7 节)可选地后跟扩大参考转换
  • 一个拆箱转换(第 5.1.8 节)可选地后跟一个扩大的原始转换。

另一方面,在赋值的情况下,允许缩小转换,只要该数字是一个常数并且适合一个简短的,cf JLS #5.2

如果变量的类型是 byte、short 或 char,并且常量表达式的值可以用变量的类型表示,则可以使用窄化原语转换。

于 2013-01-12T19:35:18.263 回答