我正在嘗試學習Java泛型,並找到以下代碼。當調用print(列表<T> a,T b)與不同的T類時發生錯誤
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
誰能幫助我理解錯誤?
你能不能也解釋了爲什麼它解析爲'Serializable'而不是任何其他公用的超類型? – Codebender
@Codebender因爲它是'ArrayList'和'Integer'之間最近常見的超類型。 「對象」將是層次結構中的一個層次。 – Tunaki
我不明白接口和類之間如何形成層次結構(我會問一個關於這個問題的新問題),但eclipse顯示它已解析爲可序列化(+1)... – Codebender