2011-03-15 62 views
1
public static void main(String args[]) 
{ 

    int[] intarray = {1, 3, 6, 8, 2, 6};   
    String[] names = {"String1", "String2", "String3", "String4", "String5", "String6"}; 

    printMe(intarray); 

} 

public static <T> void printMe(T[] i){ 
    for(T x: i) 
    { 
     System.out.println(x); 
    } 

} 

为什么编译此代码会导致此错误?将int []传递给需要T的通用方法[

The method printMe(T[]) is not applicable for the arguments (int[]) 

如果我做printMe(names)那么它的工作。

+0

[如何在Java中将int \ [\]转换为Integer \ [\]?](http://stackoverflow.com/questions/880581/how-to-convert-int-to-integer- in-java) – finnw 2011-05-24 14:51:01

+0

也涉及到:http://stackoverflow.com/questions/1467913/arrays-aslist-not-working-as-it-should – finnw 2011-05-24 14:57:46

回答

4

由于它的int不是Integer阵列,其预计在那边

+0

非常感谢。但int和Integer有什么区别?系统将Integer定义为“Integer Object”(因为我没有定义它)? – 2011-03-15 06:24:33

+0

'int'是原始数据类型,其中'Integer'是类 – 2011-03-15 06:25:19

+1

'Integer'是['java.lang.Integer'](http://download.oracle.com/javase/6/docs/api/java/ lang/Integer.html) – asgs 2011-03-15 06:26:16

1

简单的一类。泛型适用于基于Object的数据类型,而不适用于primitives

1

简单。泛型适用于基于对象的数据类型,而不适用于基元。 在String数组的情况下,它将类型强制转换为对象类型,如果int数组自动不会被转换为Object类型,则明确地指定要包含的另一个方法或使其成为Integer。