在这种情况下,类型推断按预期工作,
T
类型参数同时处理Integer
和String
:
public class A {
public static <T> void func(T obj1, T obj2) {}
public static void main(String[] args) {
A.func(1, "One");
}
}
但是,这似乎不适用于以下示例,因为出现了编译错误:
class Test<T> {
private T object;
public Test(T object) {
this.object = object;
}
}
public class A {
public static <T> void func(Test<T> one, Test<T> two) {}
public static void main(String[] args) {
Test<Integer> one = new Test<>(1);
Test<String> two = new Test<>("Two");
A.func(one, two); //compilation error
//A.<Object>func(one, two);
}
}
尽管 (例如)
Test<Object>
可以处理 Test<Integer>
和 Test<String>
,但 T
类型参数不是 推断的。为什么会出现这种情况?
func
要求两个测试具有相同类型(名为 T),但其中一个和两个具有不同的类型。