我正在尝试学习 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
谁能帮我理解错误?
最佳答案
首先你应该明白的是,使用下面的方法签名
public static <T> void print(T a, T b)
两者都是 T
必须 是同一类型,也就是说都是 a
和 b
将具有相同的推断类型。
那么为什么它适用于 new ArrayList<String>()
和 1
?因为这两个参数实际上都可以表示为 Serializable
,这是 ArrayList
的最接近的普通父类(super class)型和 Integer
:
所以在这种情况下,编译器会推断出 T
作为Serializable
.
第二种情况,带签名
public static <T> void print(List<T> a, T b)
没有通用的父类(super class)型T
这对 List<String>
都有效和 Integer
.确实String
和 Integer
是 Serializable
, 但由于 generics aren't polymorphic , 它不起作用。
关于java - 使用不同的 T 类调用 print(List<T> a, T b) 时出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34944059/