如何在没有错误的情况下实现类似的功能?
class A<K> {
void f(K x) {}
}
void foo(A<? extends X> a, X x) {
a.f(x); // AN error: The method f(capture#1-of ? extends X) in the
// type A<capture#1-of ? extends X> is not applicable for the
// arguments (X)
}
我知道它的发生是因为 'a' 可以是 A<"non-X"> 的实例,所以它的 'f' 不能接受 X 的实例作为参数,但是我怎样才能强制参数为同一类型?
这是更多代码:
测试类:
class Test {
<T> void foo(A<T> a, T x) {
a.f(x); // now it works!
}
}
在某些课程中:
Container<X> container;
public void test() {
X x = new X();
new Test().foo(container.get(), x);
}
这是容器类:
public class Container<K> {
A<? extends K> get() {
return new A<K>();
}
}