java - eclipse 错误?什么时候短不短?

标签 java eclipse

这是 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 Primitive Data Types .

最佳答案

这是因为当调用一个方法时,只有原始的扩大转换被授权,而不是原始的缩小转换(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/

相关文章:

java - 使用 Mockito 捕获两个参数

java - 如何在 Java 中使用 posix_spawn()

java - 运行在不同计算机上的 Java 程序的内存消耗

java - 在 OSGi 应用程序中获取 Eclipse 项目信息

java - 我可以使用 ObjectChangeListener 来监听任何对象的变化吗?

java - 是否可以让 Castor 编码(marshal)/取消编码(marshal) EnumMap?

eclipse - 如何使用 Eclipse 代码样式在 wordpress 中突出显示我的代码

java - 在 Java 项目中获取所有构建错误的最快方法是什么?

c - 如何在 Eclipse 中记录 C 代码(intellisense/javadoc like tooltips)

android - 我想在 eclipse 中打开 acra 项目