4

これはEclipseのバグですか?

短い変数を宣言するとき、コンパイラは整数リテラルを短いものとして扱います。

// This works
short five = 5;

ただし、整数リテラルを短いパラメータとして渡す場合は同じことを行わず、代わりにコンパイルエラーが生成されます。

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

整数リテラルがshortの範囲外にあることを明確に認識しています。

// 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で定義されています:

メソッド呼び出しコンテキストでは、次のいずれかを使用できます。

  • ID変換(§5.1.1)
  • 拡大するプリミティブ変換(§5.1.2)
  • 拡大参照変換(§5.1.5)
  • ボクシングの変換(§5.1.7)とそれに続く拡張参照変換
  • 開開変換(§5.1.8)の後に、オプションで拡張プリミティブ変換が続きます。

一方、割り当ての場合、数値が定数であり、短い値の範囲内に収まる場合は、変換を絞り込むことができます。JLS#5.2を参照してください。

変数の型がbyte、short、またはcharであり、定数式の値が変数の型で表現できる場合は、ナローイングプリミティブ変換を使用できます。

于 2013-01-12T19:35:18.263 に答える