这是 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
}
}
最佳答案
这是因为当调用一个方法时,只有原始的扩大转换被授权,而不是原始的缩小转换(int -> short 是)。这是在 JLS #5.3 中定义的:
Method invocation contexts allow the use of one of the following:
- an identity conversion (§5.1.1)
- a widening primitive conversion (§5.1.2)
- a widening reference conversion (§5.1.5)
- a boxing conversion (§5.1.7) optionally followed by widening reference conversion
- an unboxing conversion (§5.1.8) optionally followed by a widening primitive conversion.
另一方面,在赋值的情况下,缩小转换是允许的,前提是数字是一个常数并且适合一个短的,cf JLS #5.2 :
A narrowing primitive conversion may be used if the type of the variable is byte, short, or char, and the value of the constant expression is representable in the type of the variable.
关于java - eclipse 错误?什么时候短不短?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14297113/