【问题标题】:Passing an int[] to a generic method that takes a T[]将 int[] 传递给采用 T[] 的泛型方法
【发布时间】:2011-03-15 06:18:04
【问题描述】:
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);
    }

}

为什么编译这段代码会导致这个错误?

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

如果我这样做printMe(names),那么它会起作用。

【问题讨论】:

标签: java arrays generics


【解决方案1】:

因为它的数组是int 而不是Integer,所以它期待那里有一个类

【讨论】:

  • 非常感谢。但是 int 和 Integer 有什么区别?整数是否被系统定义为Integer Object(因为我没有定义它)?
  • int 是原始数据类型,其中Integer 是类
  • Integerjava.lang.Integer
  • 我的意思是它是由系统定义的吗? (我不记得定义了一个对象名称整数)
  • 是的,它包含在标准库中。检查download.oracle.com/javase/6/docs/api/java/lang/Integer.html
【解决方案2】:

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

【讨论】:

    【解决方案3】:

    简单。泛型适用于基于对象的数据类型,而不适用于原语。 在 String 数组的情况下,它是类型转换为对象类型,如果 int 数组自动转换为对象类型,那么要么明确地包含另一个方法,要么将其设为 Integer。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多