在本例中,type inference按预期工作,T
type parameter同时处理Integer
和String
:
public class A {
public static <T> void func(T obj1, T obj2) {}
public static void main(String[] args) {
A.func(1, "One");
}
}
然而,这似乎不适用于以下示例,因为出现了compilation error:
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);
}
}
尽管(for example) Test<Object>
可以同时处理Test<Integer>
和Test<String>
,但T
类型参数不是inferred.这一切为什么要发生?