小编典典

调用print时发生错误(列表 a,T b)具有不同的T类

java

我试图学习Java泛型,并发现以下代码。

public static <T> void print(T a, T b){
    System.out.println(a);
    System.out.println(b);
}

public static void main(String[] args){
    print(new ArrayList<String>(), 1);
}

哪个没有问题。

但是,当我将print方法更改为以下内容时,它给了我编译错误。

public static <T> void print(List<T> a, T b){
    System.out.println(a);
    System.out.println(b);
}

错误:

GenericTest.java:9: error: method print in class GenericTest cannot be applied to given types;
  print(new ArrayList<String>(), 1);
    ^
  required: List<T>,T
  found: ArrayList<String>,int
  reason: no instance(s) of type variable(s) T exist so that argument type int conforms to formal parameter type T
  where T is a type-variable:
    T extends Object declared in method <T>print(List<T>,T)
1 error

谁能帮助我了解错误?


阅读 423

收藏
2020-09-28

共1个答案

小编典典

您应该了解的第一件事是,使用以下方法签名

public static <T> void print(T a, T b)

双方T 必须 是同一类型,也就是既ab将具有相同infered类型。

那么,为什么它的工作new ArrayList<String>()1?因为这两个参数实际上可以表示为Serializable,这是最近的公用超类型ArrayListInteger

  • ArrayList实现Serializable接口。
  • 1可以装进一个盒子Integer,也可以Serializable

因此,在这种情况下,编译器将推断TSerializable


在第二种情况下,带有签名

public static <T> void print(List<T> a, T b)

没有通用的超级类型TList<String>和均有效IntegerString和两者Integer都是对的Serializable,但是由于泛型不是多态的,所以它不起作用。

2020-09-28