如果有人可以向我解释为什么u = bar(u,r)在以下代码中无效,我会非常感激.我找不到正确的解释.
class R {
}
class U {
}
public class Foo {
public static <T> T bar(T x, T y) {
return x;
}
public static void main(String[] args) {
R r = new R();
U u = new U();
u = bar(u,r); // why is this not working?
}
}
Run Code Online (Sandbox Code Playgroud)
更新:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Type mismatch: cannot convert from Object to U
Run Code Online (Sandbox Code Playgroud)
在确定用于泛型类型的类型时T,Java会查看参数的类型.
在这种情况下,参数u和r不同的,不相关的类型(U和R).
因此Object,它们最接近的共同祖先是,所以返回类型将是Object,需要一个演员才能被分配u.