我试图学习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方法更改为以下内容时,它给了我编译错误。
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
谁能帮助我了解错误?
您应该了解的第一件事是,使用以下方法签名
public static <T> void print(T a, T b)
双方T 必须 是同一类型,也就是既a和b将具有相同infered类型。
T
a
b
那么,为什么它的工作new ArrayList<String>()和1?因为这两个参数实际上可以表示为Serializable,这是最近的公用超类型ArrayList和Integer:
new ArrayList<String>()
1
Serializable
ArrayList
Integer
因此,在这种情况下,编译器将推断T为Serializable。
在第二种情况下,带有签名
public static <T> void print(List<T> a, T b)
没有通用的超级类型T对List<String>和均有效Integer。String和两者Integer都是对的Serializable,但是由于泛型不是多态的,所以它不起作用。
List<String>
String