简体   繁体   English

将int []传递给采用T []的通用方法

[英]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. 如果我执行printMe(names)那么它可以工作。

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

Simple. 简单。 Generics are meant for Object -based datatypes and not for primitives . 泛型适用于基于Object的数据类型,而不适用于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. 在String数组的情况下,它将类型转换为对象类型,在int数组的情况下,它将自动转换为对象类型,因此,明确地要包含另一种方法或将其设置为Integer。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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