2011-12-29 76 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-ARGS。

如果我阵列声明为

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

回答

2

这是因为自动装箱可以从原始只会发生在它的包装(如intInteger),而不是从一个原始的阵列到相应包装的数组。与autounboxing类似的情况。

例如如果你定义的测试方法如下:

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

如下,你可以这样做:

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 

然后什么如下将失败:

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 S上的阵列,它工作不是Integer秒的阵列。编译器试图在引擎盖下做到这一点。所以你不能做你想做的事。

您可以坚持使用一种数组,或使用commons-lang中的ArrayUtils.toPrimitive(..)

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

这就是为什么它抱怨。

+0

w帽子是班[我? – ziggy 2011-12-29 15:53:12

+0

这是int数组的类类型。我 - 代表int,[ - 代表一维数组 – 2011-12-29 15:58:57

1

您传递方法的内容与预期的内容不符。你将我设置为Integer对象的数组。然后你将它传递给方法test()。你已经定义的唯一方法test是一个基本类型的int(Integer!= int)。您可以快速解决它通过改变测试的函数定义为:

public static void test(Integer[] s){