2011-12-29 7 views
1

コンパイルに失敗したのはなぜですか?var-argへのラッパークラスのアンボック

class ZiggyTest { 

    public static void main(String[] args){ 

     Integer[] i = {1,2,3,4}; 
     test(i); 

    } 

    public static void test(int... s){ 
     for (int x : s){ 
      System.out.println(x); 
     } 
    } 
} 

ZiggyTest.java:26: test(int...) in ZiggyTest cannot be applied to (java.lang.Integer[]) 
     test(i); 
     ^
1 error 

それはVAR-引数にアンボクシングラッパーアレイに来るときのルールは何ですか。

iは

int[] j = {1,2,3,4}; 
test(j); 

答えて

2

オートボクシングが唯一のプリミティブから、それは(Integerに例えばint)のラッパーだに発生する可能性があるためだことはなく、プリミティブの配列からに対応するラッパーの配列autounboxingの場合も同様です。

あなたのテストメソッドを定義する場合、以下のように、

Integer n = 1; // autoboxing happens here too 
test(n); //this is a valid call because n is autounboxed 

を:しかし

public static void test(int[] n) {} //<-- param n is an array of int primitives 

その後、何かを次のように

public static void test(int n) {} //<-- param n is of type int primitive 

は、あなたが何かをすることができます:あなたはあなたのテストメソッドを定義する場合、以下のように次のように失敗します。

Integer[] ns = {1, 2}; // no autboxing here because we are dealing with array (just a syntactic sugar) 
// Integer[] ns = new int[]{1, 2}; // something like this is not valid 
test(ns); // this will fail       
3

としてintの配列を配列を宣言する場合、それが動作しないがIntegerの配列ではありません。そしてコンパイラはそれをフードの下でしようとします。だから、あなたが望むことをすることはできません。

1つのタイプの配列を使用するか、commons-langのArrayUtils.toPrimitive(..)を使用できます。

1
int[].class != Integer[].class. 
int[].class = class [I 
Integer[].class = class [Ljava.lang.Integer; 

それは不平を言っている理由です。

+0

w帽子はクラスですか? – ziggy

+0

これはint型のクラス型です。 i - intを表し、 - は1次元配列を表す –

1

メソッドを渡しているものが、定義されているものと一致しません。 iをIntegerオブジェクトの配列として設定します。次に、メソッドtest()に渡します。あなたが定義した唯一のメソッドtestは、プリミティブ型(Integer!= int)であるintが必要です。あなたは、迅速にするために、テストの関数定義を変更することで、それを解決することができます

public static void test(Integer[] s){ 
関連する問題