简体   繁体   中英

Passing an int[] to a generic method that takes a T[]

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);
    }

}

Why does compiling this code result in this error?

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

If I do printMe(names) then it works.

因为它的int数组不是Integer ,所以它在那儿期望一个类

Simple. Generics are meant for Object -based datatypes and not for primitives .

Simple. Generics are meant for Object-based datatypes and not for primitives. In the case of String array it is type casting to object type, in case int array automatically it is not casted to Object type, So either explicitely another method to be included or make it Integer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM